package com.cci.kangdao.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.cipFleet.dto.response.CipHealthCheckResponse;
import com.cci.kangdao.cipapi.*;
import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeEntity;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.*;
import com.cci.kangdao.dto.PagedResponse;
import com.cci.kangdao.dto.request.ButlerRequest;
import com.cci.kangdao.dto.request.CertifiedMessagePushRequest;
import com.cci.kangdao.dto.response.CustomerEngineRelResponse;
import com.cci.kangdao.dto.response.GetCommercialCarListResponse;
import com.cci.kangdao.enums.BindAddMessageStatus;
import com.cci.kangdao.externalData.service.ExternalDataSynchroService;
import com.cci.kangdao.model.BatchBindVehiclesInfo;
import com.cci.kangdao.model.ButlerInfo;
import com.cci.kangdao.model.ConductionInfo;
import com.cci.kangdao.model.VehicleInfo;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.*;
import com.cci.kangdao.utilTool.*;
import com.gexin.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service("CustomerEngineRelService")
public class CustomerEngineRelImpl implements CustomerEngineRelService {

    private Logger log = Logger.getLogger(this.getClass().getName());

    //活动编号
    private static final String INVITE = "invite";

    @Value("${mc.messagePushUrl}")
    private String messagePushUrl;
    @Resource
    private CustomerEngineRelDao customerEngineRelDao;
    @Resource
    private EngineMsgDao engineMsgDao;
    @Autowired
    private WorkOrderTServiceImpl workOrderTServiceImpl;
    @Resource
    private AsyncCrmService asyncCrmService;
    @Autowired
    private ServiceAgrementDao saDao;
    @Resource
    private InviteUserService inviteUserService;
    @Resource
    private InviteDao inviteDao;
    @Resource
    private CipVehicleMapper cipVehicleMapper;
    @Resource
    private DictionariesTDao dictionariesTDao;
    @Autowired
    private SyncEsnAndUserId syncEsnAndUserId;
    @Autowired
    private CertifiedOwnerApplyDao certifiedOwnerApplyDao;
    @Autowired
    private CertifiedOwnerApplyRecordDao certifiedOwnerApplyRecordDao;
    @Autowired
    private UserTDao userTDao;
    @Resource
    private EngineMasterDataMapper engineMasterDataMapper;
    @Resource
    private ServiceAgrementDao serviceAgrementDao;
    @Autowired
    private CustomerAmtRelMapper customerAmtRelMapper;
    @Autowired
    private EngineMsgServiceImpl engineMsgService;
    @Autowired
    private CustomerEngineRelLoadMsgRelationService loadMsgRelationService;
    @Resource
    private XgjGetUserInfoDao xgjGetUserInfoMapper;
    @Resource
    private ServiceStationDao serviceStationDaoMapper;
    @Autowired
    private RedisClientUtils redisClientUtils;
    @Resource
    private OcrVehicleLicenseTMapper ocrVehicleLicenseTMapper;
    @Resource
    private CipServiceApi cipServiceApi;
    @Resource
    private RegularLocationMapper regularLocationMapper;
    @Resource
    private ExternalDataSynchroService externalDataSynchroService;
    @Resource
    private UserChannelTMapper userChannelTMapper;

    /**
     * 根据用户id获取设备列表     支持ccec
     */
    @Override
    public ModelAndView getCustomerEngineRel(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        String keyword = MapUtils.getString(map, "keyword");
        Map<String, Object> queryMap = new HashMap<>(2);
        queryMap.put("userId", userT.getId());
        queryMap.put("keyword", keyword);
        if (MapUtils.getInteger(map, "associationType") != null) {
            queryMap.put("associationType", MapUtils.getString(map, "associationType"));
        }
        List<Map<String, Object>> customerEngineRelList = customerEngineRelDao.getCustomerEngineRelList(queryMap);
        Map<String, Object> data = new HashMap<>(1);
        data.put("customerEngineRelList", customerEngineRelList);
        ParameterTool.writeSuccessResponse(response, data);
        return null;
    }

    /**
     * 分页设备列表
     */
    @Override
    public ModelAndView getPageCustomerEngineList(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        String keyword = MapUtils.getString(map, "keyword");
        Map<String, Object> queryMap = new HashMap<>(2);
        queryMap.put("userId", userT.getId());
        queryMap.put("keyword", keyword);
        if (MapUtils.getInteger(map, "associationType") != null) {
            queryMap.put("associationType", MapUtils.getString(map, "associationType"));
        }
        //处理分页信息
        int page = 1;
        if (map.get("page") != null) {
            page = MapUtils.getInteger(map, "page", 1);
        }
        int pagesize = 50;
        if (map.get("pagesize") != null) {
            pagesize = MapUtils.getInteger(map, "pagesize", 50);
        }
        //分页处理，显示第一页的10条数据
        PageHelper.startPage(page, pagesize);
        List<Map<String, Object>> customerEngineRelList = customerEngineRelDao.getCustomerEngineRelList(queryMap);
        Map<String, Object> data = new HashMap<>(1);
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(customerEngineRelList);
        data.put("customerEngineRelList", pageInfo.getList());
        data.put("pageNum", pageInfo.getPageNum());
        data.put("pageSize", pageInfo.getPageSize());
        data.put("size", pageInfo.getSize());
        data.put("total", customerEngineRelDao.getCustomerEngineRelCount(userT.getId()));
        ParameterTool.writeSuccessResponse(response, data);
        return null;
    }

    /**
     * 管家服务列表
     */
    @Override
    public PagedResponse<ButlerInfo> getButlerServiceList(ButlerRequest request) {
        UserT userT = UserThreadLocal.get();
        if (null == request.getPage()) {
            request.setPage(1);
        }
        if (null == request.getPageSize()) {
            request.setPageSize(50);
        }
        request.setUserId(userT.getId());
        PageHelper.startPage(request.getPage(), request.getPageSize());
        List<ButlerInfo> list = customerEngineRelDao.getButlerServiceList(request);
        PageInfo<ButlerInfo> pageInfo = new PageInfo<>(list);
        PagedResponse<ButlerInfo> response =  BeanUtils.convert(pageInfo, PagedResponse.class);
        response.setList(list);
        return response;
    }

    /**
     * 修改 管家服务
     */
    @Override
    public boolean updateButlerService(ButlerInfo info) {
        UserT userT = UserThreadLocal.get();
        if(info.getType() == 1){
            List<CustomerEngineRelT> list = customerEngineRelDao.getListByUserId(userT.getId());
            if(CollectionUtils.isNotEmpty(list)){
                List<Long> idList = list.stream().map(CustomerEngineRelT::getId).filter(a -> null != a).collect(Collectors.toList());
                info.setIdList(idList);
            }
        }
        if(CollectionUtils.isNotEmpty(info.getIdList())){
            for(Long id : info.getIdList()){
                ServiceStationT serviceStationT = serviceStationDaoMapper.getStationByStationNo(info.getBusinessNo());
                if (null != serviceStationT) {
                    CustomerEngineRelT customerEngineRelT = customerEngineRelDao.getCustomerEngineRelById(id);
                    //绑车数据至芯管家后台
                    if (null != customerEngineRelT) {
                        int i = customerEngineRelDao.updateBusinessNoById(info.getBusinessNo(), id, userT.getId(), LocalTimeUtil.getRealCurrentTime());
                        int dataSource = 2;
                        FleetAndEsnRelationRequest xgjRequest = new FleetAndEsnRelationRequest();
                        xgjRequest.setEsn(customerEngineRelT.getEsn());
                        xgjRequest.setPlatenum(customerEngineRelT.getVin());
                        xgjRequest.setDataSource(dataSource);
                        xgjRequest.setUserId(userT.getId());
                        xgjRequest.setVehicleType(1);
                        xgjRequest.setVin(customerEngineRelT.getNewVIN());
                        if (StringUtils.isBlank(info.getBusinessNo()) && StringUtils.isNotBlank(customerEngineRelT.getBusinessNo())) {
                            xgjRequest.setBusinessNo(customerEngineRelT.getBusinessNo());
                            xgjRequest.setOperate("D");
                        } else if (StringUtils.isNotBlank(info.getBusinessNo())) {
                            xgjRequest.setBusinessNo(info.getBusinessNo());
                            List<String> stationNameList = xgjGetUserInfoMapper.getVehicleListByEsn(customerEngineRelT.getEsn(), serviceStationT.getStationno());
                            if (CollectionUtils.isNotEmpty(stationNameList)) {
                                xgjRequest.setOperate("U");
                            } else {
                                xgjRequest.setOperate("I");
                            }
                        }
                        cipServiceApi.syncBindVehicle(xgjRequest, userT.getId());
                    }
                }
            }
        }
        return true;
    }

    /**
     * 获取用户历史设备列表
     */
    @Override
    public ModelAndView getHistoryCustomerEngineRel(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        String keyword = MapUtils.getString(map,"keyword");
        Map<String,Object> queryMap = new HashMap<>(2);
        queryMap.put("userId",userT.getId());
        queryMap.put("keyword",keyword);
        List<Map<String, Object>> customerEngineRelList = customerEngineRelDao.getHistoryCustomerEngineRel(queryMap);
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(customerEngineRelList)) {
            for (Map<String, Object> dataMap : customerEngineRelList) {
                Map<String, Object> subData = new HashMap<>();
                subData.put("ID", MapUtils.getLong(dataMap, "cerID"));
                subData.put("EngineMsgId", MapUtils.getLong(dataMap, "id"));
                subData.put("ESN", MapUtils.getString(dataMap, "ESN"));
                subData.put("SMN", MapUtils.getString(dataMap, "SMN", ""));
                subData.put("VIN", MapUtils.getString(dataMap, "VIN", ""));
                subData.put("OEMID", 0L);
                //OEMName不取发动机表字段，取用户绑定设备表数据
                subData.put("OEMName", MapUtils.getString(dataMap, "OEMName", ""));
                subData.put("EngineType", MapUtils.getString(dataMap, "engineType", ""));
                subData.put("WarrantyStartDate", MapUtils.getString(dataMap, "WarrantyStartDate", ""));
                subData.put("Application", MapUtils.getString(dataMap, "Application", ""));
                subData.put("MarketType", MapUtils.getString(dataMap, "MarketType", ""));
                subData.put("ShoppingDate", MapUtils.getString(dataMap, "ShoppingDate", ""));
                //以下是ccec渠道所需字段
                subData.put("SONo",MapUtils.getString(dataMap,"SONo",""));
                subData.put("Series",MapUtils.getString(dataMap,"Series",""));
                subData.put("ISWarrantyStart",MapUtils.getIntValue(dataMap,"ISWarrantyStart",2));
                //subData.put("engineType",MapUtils.getString(dataMap,"engineType",""));
                subData.put("EstimateWarrantyStartDate",MapUtils.getString(dataMap,"EstimateWarrantyStartDate",""));
                subData.put("EngineProducedDate",MapUtils.getString(dataMap,"EngineProducedDate",""));
                //是否是大运发动机
                int oemFlag = MapUtils.getIntValue(dataMap,"OEMFlag",0);
                if(oemFlag == 1){
                    subData.put("OEMFlag",1);
                }else{
                    subData.put("OEMFlag",0);
                }
              /*  subData.put("EquipmentType",MapUtils.getString(dataMap,"EquipmentType",""));*/
                subData.put("DrivingLicensePhotoUrl",MapUtils.getString(dataMap,"DrivingLicensePhotoUrl",""));
                subData.put("EquipmentPhotoUrl",MapUtils.getString(dataMap,"EquipmentPhotoUrl",""));
                subData.put("NewVIN",MapUtils.getString(dataMap,"NewVIN",""));
                /*subData.put("EquipmentUse",MapUtils.getString(dataMap,"EquipmentUse",""));
                subData.put("EquipmentUseName",MapUtils.getString(dataMap,"EquipmentUseName",""));*/
                subData.put("ServiceStationId",MapUtils.getString(dataMap,"ServiceStationId",""));
                subData.put("ServiceStationName",MapUtils.getString(dataMap,"ServiceStationName",""));
                subData.put("EsnPowerType",MapUtils.getIntValue(dataMap,"EsnPowerType",-1));
                subData.put("EsnApplicationType",MapUtils.getIntValue(dataMap,"EsnApplicationType",-1));
                subData.put("Flag",MapUtils.getIntValue(dataMap,"Flag"));
                subData.put("IsCancelledAuth", MapUtils.getIntValue(dataMap, "IsCancelledAuth"));
                subData.put("associationType", MapUtils.getString(dataMap, "associationType", ""));
                subData.put("housekeepStatus", MapUtils.getIntValue(dataMap, "housekeepStatus"));
                dataList.add(subData);
            }
        }
        Map<String, Object> data = new HashMap<>(1);
        data.put("customerEngineRelList", dataList);
        ParameterTool.writeSuccessResponse(response, data);
        return null;
    }

    /**
     * 根据esn获取用户设备详细接口
     */
    @Override
    public ModelAndView getCustomerEngineByEsn(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        String esn = MapUtils.getString(map,"esn");
        if(StringUtils.isEmpty(esn)){
            ParameterTool.writeErrorResponse(response,-5);
            return null;
        }

        CustomerEngineRelT customerEngineRelT = customerEngineRelDao.getCustomerEngineRelByEsn(userT.getId(),esn);

        ParameterTool.writeSuccessResponse(response, customerEngineRelT);
        return null;
    }


    /**
     * 根据CustomerEngine表主键id获取设备信息详情
     */
    @Override
    public ModelAndView getCustomerEngineById(Map<String, Object> map) {
        UserT userT = UserThreadLocal.get();
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        Long customerEngineRelID = MapUtils.getLongValue(map,"customerEngineRelID",-1);
        String esn = MapUtils.getString(map,"esn");
        Map<String, Object> customerEngineRelMap = new HashMap<>();
        if(-1 != customerEngineRelID){
            customerEngineRelMap = customerEngineRelDao.getCustomerEngineById(customerEngineRelID);
        } else if(StringUtils.isNotBlank(esn)){
            customerEngineRelMap = customerEngineRelDao.getCustomerEngineByUserId(userT.getId(),esn);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("ID", MapUtils.getLong(customerEngineRelMap, "cerID"));
        data.put("EngineMsgId", MapUtils.getLong(customerEngineRelMap, "id"));
        data.put("ESN", MapUtils.getString(customerEngineRelMap, "ESN"));
        data.put("SMN", MapUtils.getString(customerEngineRelMap, "SMN", ""));
        data.put("VIN", MapUtils.getString(customerEngineRelMap, "VIN", ""));
        data.put("OEMID", 0L);
        //OEMName不取发动机表字段，取用户绑定设备表数据
        data.put("OEMName", MapUtils.getString(customerEngineRelMap, "OEMName", ""));
        data.put("EngineType", MapUtils.getString(customerEngineRelMap, "engineType", ""));
        data.put("WarrantyStartDate", MapUtils.getString(customerEngineRelMap, "WarrantyStartDate", ""));
        data.put("Application", MapUtils.getString(customerEngineRelMap, "Application", ""));
        data.put("MarketType", MapUtils.getString(customerEngineRelMap, "MarketType", ""));
        data.put("ShoppingDate", MapUtils.getString(customerEngineRelMap, "ShoppingDate", ""));
        //以下是ccec渠道所需字段
        data.put("SONo",MapUtils.getString(customerEngineRelMap,"SONo",""));
        data.put("Series",MapUtils.getString(customerEngineRelMap,"Series",""));
        data.put("ISWarrantyStart",MapUtils.getIntValue(customerEngineRelMap,"ISWarrantyStart",2));
        //subData.put("engineType",MapUtils.getString(dataMap,"engineType",""));
        data.put("EstimateWarrantyStartDate",MapUtils.getString(customerEngineRelMap,"EstimateWarrantyStartDate",""));
        data.put("EngineProducedDate",MapUtils.getString(customerEngineRelMap,"EngineProducedDate",""));
        data.put("EquipmentType",MapUtils.getIntValue(customerEngineRelMap,"EquipmentType"));
        data.put("DrivingLicensePhotoUrl",MapUtils.getString(customerEngineRelMap,"DrivingLicensePhotoUrl",""));
        data.put("EquipmentPhotoUrl",MapUtils.getString(customerEngineRelMap,"EquipmentPhotoUrl",""));
        data.put("NewVIN",MapUtils.getString(customerEngineRelMap,"NewVIN",""));
        data.put("EquipmentUse",MapUtils.getIntValue(customerEngineRelMap,"EquipmentUse"));
        data.put("EquipmentUseName",MapUtils.getString(customerEngineRelMap,"EquipmentUseName",""));
        data.put("ServiceStationId",MapUtils.getIntValue(customerEngineRelMap,"ServiceStationId"));
        data.put("ServiceStationName",MapUtils.getString(customerEngineRelMap,"ServiceStationName",""));
        data.put("OcrESN",MapUtils.getString(customerEngineRelMap,"OcrESN",""));
        data.put("OcrVIN",MapUtils.getString(customerEngineRelMap,"OcrVIN",""));
        data.put("OcrPlateNumber",MapUtils.getString(customerEngineRelMap,"OcrPlateNumber",""));
        data.put("DrivingLicensePageUrl",MapUtils.getString(customerEngineRelMap,"DrivingLicensePageUrl",""));
        data.put("OcrTotalMass",MapUtils.getFloat(customerEngineRelMap,"OcrTotalMass"));
        data.put("OcrUnladenMass",MapUtils.getFloat(customerEngineRelMap,"OcrUnladenMass"));
        data.put("OcrApprovedLoadCapacity",MapUtils.getFloat(customerEngineRelMap,"OcrApprovedLoadCapacity"));
        data.put("OcrGabariteLength",MapUtils.getFloat(customerEngineRelMap,"OcrGabariteLength"));
        data.put("OcrGabariteWidth",MapUtils.getFloat(customerEngineRelMap,"OcrGabariteWidth"));
        data.put("OcrGabariteHeight",MapUtils.getFloat(customerEngineRelMap,"OcrGabariteHeight"));
        data.put("OcrTractionMass",MapUtils.getFloat(customerEngineRelMap,"OcrTractionMass"));
        data.put("IsDrivingLicensePage", MapUtils.getInteger(customerEngineRelMap, "IsDrivingLicensePage"));
        data.put("BusinessNo", MapUtils.getString(customerEngineRelMap, "BusinessNo"));
        data.put("InviteCode", MapUtils.getString(customerEngineRelMap, "InviteCode"));

        data.put("IsImproveCarMsg",MapUtils.getInteger(customerEngineRelMap,"IsImproveCarMsg"));
        data.put("OcrVehicleType",MapUtils.getInteger(customerEngineRelMap,"OcrVehicleType"));
        data.put("OcrApplicationClass", MapUtils.getInteger(customerEngineRelMap, "OcrApplicationClass"));
        data.put("FinalVehicleType", MapUtils.getInteger(customerEngineRelMap, "FinalVehicleType"));
        data.put("FinalApplicationClass", MapUtils.getInteger(customerEngineRelMap, "FinalApplicationClass"));
        data.put("FinalTotalMass", MapUtils.getFloat(customerEngineRelMap, "FinalTotalMass"));
        data.put("FinalApprovedLoadCapacity", MapUtils.getFloat(customerEngineRelMap, "FinalApprovedLoadCapacity"));
        data.put("FinalGabariteLength", MapUtils.getFloat(customerEngineRelMap, "FinalGabariteLength"));
        data.put("FinalGabariteWidth", MapUtils.getFloat(customerEngineRelMap, "FinalGabariteWidth"));
        data.put("FinalGabariteHeight", MapUtils.getFloat(customerEngineRelMap, "FinalGabariteHeight"));
        data.put("FinalAxlesNum", MapUtils.getInteger(customerEngineRelMap, "FinalAxlesNum"));
        data.put("associationType", MapUtils.getString(customerEngineRelMap, "associationType", ""));
        data.put("housekeepStatus", MapUtils.getIntValue(customerEngineRelMap, "housekeepStatus"));
        //添加常用地址
        CustomerEngineRelLoadMsgRelationT isRecommendClass = loadMsgRelationService.getIsRecommendClass(customerEngineRelID);
        // private String startingPoint;
        //
        //    private String endPoint;
        //
        //    private Integer isRecommend;
        //
        //    private String startLongitude;
        //    private String startLatitude;
        //    private String endLongitude;
        //    private String endLatitude;
        data.put("StartingPoint", isRecommendClass == null ? "" : isRecommendClass.getStartingPoint());
        data.put("EndPoint", isRecommendClass == null ? "" : isRecommendClass.getEndPoint());
        data.put("StartLongitude", isRecommendClass == null ? "" : isRecommendClass.getStartLongitude());
        data.put("StartLatitude", isRecommendClass == null ? "" : isRecommendClass.getStartLongitude());
        data.put("EndLongitude", isRecommendClass == null ? "" : isRecommendClass.getEndLongitude());
        data.put("EndLatitude", isRecommendClass == null ? "" : isRecommendClass.getEndLatitude());
        //查询ocr的记录
        OcrVehicleLicenseT ocrVehicleLicenseT = new OcrVehicleLicenseT();
        ocrVehicleLicenseT.setCustomerEngineId(MapUtils.getLong(customerEngineRelMap, "cerID"));
        Map ocrVehicleLicenseMap  = ocrVehicleLicenseTMapper.selectListLast(ocrVehicleLicenseT);
        data.put("OcrVehicleLicense", ocrVehicleLicenseMap == null ? "" : ocrVehicleLicenseMap);
        ParameterTool.writeSuccessResponse(response, data);
        return null;
    }



    /**
     * 用户添加设备信息接口
     */
    @Override
    @Transactional
    public ModelAndView addCustomerEngineRel(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        try {
            UserT userT = UserThreadLocal.get();
            map.put("userId", userT.getId());
            map.put("phone", userT.getPhone());
            // 获取实际当前时间(服务器时间加8小时)
            map.put("CreateTime", LocalTimeUtil.getRealCurrentTime());

            // 验证ESN是否重复
            String esn = MapUtils.getString(map, "ESN", "");
            int num = customerEngineRelDao.getRelationByUserIdAndESN(userT.getId(),esn);
            if (num > 0) {
                ParameterTool.writeErrorResponse(response, -15);
            } else if (!this.esnByCheck(esn)) {
                ParameterTool.writeErrorResponse(response, -46);
            } else {
                EngineMsg engineMsg = engineMsgDao.getEngineMsgByESNString(esn);
                //调用cip接口获取esn信息
                EsnBasicInfoEntity esnInfo = null;
                CipResponeEntity respone = CipApiUtils.getCipServiceApi().getEsnInfo(esn);
                if(null != respone ){
                    map.put("cipReturnValue", JSON.toJSON(respone).toString());
                    if(respone.getCode().equals(0)){
                        esnInfo = (EsnBasicInfoEntity) JSONObject.toBean(respone.getData(), EsnBasicInfoEntity.class);
                    }
                }
                String smn = MapUtils.getString(map,"SMNName","");
                Map<String, Object> engineMsgMap = new HashMap<>();
                int fleetEmissionLevelDInt = -1;
                int fleetFuelTypeDInt = -1;
                //设置排放信息
                if(null != esnInfo){
                    //排放等级
                    String emissionLevel = esnInfo.getEmissionLevel();
                    //燃油类型
                    String fuelType = esnInfo.getFuelType();
                    //获取字典表应用类型map(调用cip接口返回的应用类型枚举值)
                    Map<String,Map<String,Object>> fleetEmissionLevelDicListMap = dictionariesTDao.getDicListByDtableName("fleetEmissionLevel");
                    if(MapUtils.isNotEmpty(fleetEmissionLevelDicListMap) && StringUtils.isNotEmpty(emissionLevel) && fleetEmissionLevelDicListMap.containsKey(emissionLevel)){
                        Map<String,Object> fleetEmissionLevelDicMap = MapUtils.getObject(fleetEmissionLevelDicListMap,emissionLevel);
                        if(MapUtils.isNotEmpty(fleetEmissionLevelDicMap)){
                            fleetEmissionLevelDInt = MapUtils.getIntValue(fleetEmissionLevelDicMap,"DInt",-1);
                        }
                    }
                    //获取字典表动力类型ma(调用cip接口返回的应用类型枚举值)
                    Map<String,Map<String,Object>> fleetFuelTypeDicListMap = dictionariesTDao.getDicListByDtableName("fleetFuelType");
                    if(MapUtils.isNotEmpty(fleetFuelTypeDicListMap) && StringUtils.isNotEmpty(fuelType) && fleetFuelTypeDicListMap.containsKey(fuelType)){
                        Map<String,Object> fleetFuelTypeDicMap = MapUtils.getObject(fleetFuelTypeDicListMap,fuelType);
                        if(MapUtils.isNotEmpty(fleetFuelTypeDicMap)){
                            fleetFuelTypeDInt = MapUtils.getIntValue(fleetFuelTypeDicMap,"DInt",-1);
                        }
                    }
                    engineMsgMap.put("model", emissionLevel);
                }
                engineMsgMap.put("EsnPowerType",fleetFuelTypeDInt);
                engineMsgMap.put("EsnApplicationType",fleetEmissionLevelDInt);
                if(null == engineMsg){
                    engineMsgMap.put("ESN", MapUtils.getString(map,"ESN"));
                    if(StringUtils.isEmpty(smn)){  //如果前端传的smn是空的   调用sibel接口
                        EngineMasterData engineMasterData = engineMasterDataMapper.selectByesn(esn);
                        if(null != engineMasterData){
                            smn = engineMasterData.getServiceModelName();
                        }
                        if(StringUtils.isEmpty(smn)) {
                            Map<String, Object> getSMNBySibel = workOrderTServiceImpl.getSMNBySibel(request, esn);
                            if (MapUtils.isNotEmpty(getSMNBySibel)) {
                                Map<String, Object> data = (Map<String, Object>) MapUtils.getMap(getSMNBySibel, "data");
                                smn = MapUtils.getString(data, "SMN", "");
                            }
                        }
                    }
                    engineMsgMap.put("SMN", smn);
                    if(StringUtils.isBlank(MapUtils.getString(map,"VIN"))){
                        map.put("VIN", MapUtils.getString(map, "ESN"));
                    }
                    engineMsgMap.put("equipmentNo", MapUtils.getString(map,"VIN"));

                    engineMsgMap.put("vehicleCompany", MapUtils.getString(map,"OEMName"));
                    engineMsgMap.put("engineType", MapUtils.getString(map,"engineType"));
                    //engineMsgMap.put("manufactor", ""); //未传输
                    engineMsgMap.put("serviceChannel", MapUtils.getString(map,"serviceChannel"));
                    //engineMsgMap.put("saleDate", ""); //未传输
                    engineMsgMap.put("marketType", MapUtils.getString(map,"marketType"));
                    engineMsgMap.put("application", MapUtils.getString(map,"application"));
                    engineMsgMap.put("warrantyStartDate", MapUtils.getString(map,"warrantyStartDate"));
                    engineMsgMap.put("shoppingDate", MapUtils.getString(map, "shoppingDate"));
                    //以下是ccec字段
                    if("CCEC".equals(MapUtils.getString(map,"serviceChannel",""))){
                        engineMsgMap.put("series", MapUtils.getString(map, "series"));
                        engineMsgMap.put("estimateWarrantyStartDate", MapUtils.getString(map, "estimateWarrantyStartDate"));
                        engineMsgMap.put("soNo", MapUtils.getString(map, "soNo"));
                        engineMsgMap.put("isWarrantyStart", MapUtils.getIntValue(map, "isWarrantyStart",2));
                    }
                    //保存发动机信息
                    engineMsgDao.newInsertEngineMsg(engineMsgMap);
                    //将新插入发动机信息ID放入关联表中
                    map.put("EngineMsgId", MapUtils.getLong(engineMsgMap, "id"));
                }else{
                    if(StringUtils.isEmpty(smn) && StringUtils.isEmpty(engineMsg.getSMN())){
                        EngineMasterData engineMasterData = engineMasterDataMapper.selectByesn(esn);
                        if(null != engineMasterData){
                            smn = engineMasterData.getServiceModelName();
                        }
                        if(StringUtils.isEmpty(smn)) {
                            Map<String, Object> getSMNBySibel = workOrderTServiceImpl.getSMNBySibel(request, esn);
                            if (MapUtils.isNotEmpty(getSMNBySibel)) {
                                Map<String, Object> data = (Map<String, Object>) MapUtils.getMap(getSMNBySibel, "data");
                                smn = MapUtils.getString(data, "SMN", "");
                            }
                        }
                    }
                    if(StringUtils.isNotEmpty(smn)){
                        engineMsgMap.put("SMN", smn);
                    }
                    if(StringUtils.isBlank(MapUtils.getString(map,"VIN"))){
                        map.put("VIN", MapUtils.getString(map, "ESN"));
                        engineMsgMap.put("equipmentNo",engineMsg.getEquipmentNo());
                    } else {
                        engineMsgMap.put("equipmentNo", MapUtils.getString(map,"VIN"));
                    }
                    engineMsgMap.put("vehicleCompany", MapUtils.getString(map,"OEMName"));
                    engineMsgMap.put("engineType", MapUtils.getString(map,"engineType"));
                    //engineMsgMap.put("manufactor", ""); //未传输
                    engineMsgMap.put("serviceChannel", MapUtils.getString(map,"serviceChannel"));
                    //engineMsgMap.put("saleDate", ""); //未传输
                    engineMsgMap.put("marketType", MapUtils.getString(map,"marketType"));
                    engineMsgMap.put("application", MapUtils.getString(map,"application"));
                    engineMsgMap.put("warrantyStartDate", MapUtils.getString(map,"warrantyStartDate"));
                    engineMsgMap.put("shoppingDate", MapUtils.getString(map, "shoppingDate"));
                    engineMsgMap.put("id", engineMsg.getId());
                    //以下是ccec字段
                    if("CCEC".equals(MapUtils.getString(map,"serviceChannel",""))){
                        engineMsgMap.put("series", MapUtils.getString(map, "series"));
                        engineMsgMap.put("estimateWarrantyStartDate", MapUtils.getString(map, "estimateWarrantyStartDate"));
                        engineMsgMap.put("soNo", MapUtils.getString(map, "soNo"));
                        engineMsgMap.put("isWarrantyStart", MapUtils.getIntValue(map, "isWarrantyStart",2));
                    }
                    if(null == esnInfo){
                        engineMsgMap.put("model", engineMsg.getModel());
                    }
                    engineMsgDao.updateEngineMsg(engineMsgMap);
                    map.put("EngineMsgId", engineMsg.getId());
                }

                //活动绑车拉新
                //获取活动信息 活动期间报的问题
                ActivityT activity = inviteDao.getActivity(INVITE);
                if(null != activity && activity.getIsOpen().equals(1)
                        && StringUtils.isNotEmpty(activity.getEndTime())
                        && LocalTimeUtil.isBefore(LocalTimeUtil.getRealCurrentTime(),activity.getEndTime())){
                    int bindAddStatus = 0;
                    if (null != esnInfo) {
                        bindAddStatus = inviteUserService.addBind(esn, esnInfo.getEmissionLevel());
                    } else {
                        bindAddStatus = BindAddMessageStatus.BAOCUO.getStatus();
                    }
                    map.put("bindAddStatus", bindAddStatus);
                    map.put("bindAddMessage", BindAddMessageStatus.getDescByCode(bindAddStatus));
                }
                //百万圆桌绑车
                inviteUserService.addBwyzBind(esn, userT.getId());
                //首次绑车添加蜜值
                int customerEngineRelTCount = customerEngineRelDao.getCountByUserId(userT.getId());
                if (customerEngineRelTCount <= 0) {
                    //同步添加蜜值的方法
                    syncAddhoney(request);
                }
                customerEngineRelDao.addCustomerEngineRel(map);

                Long count = saDao.isSignAgreement(userT.getId(), LocalTimeUtil.getRealCurrentTime());
                if (count > 0) {//用户如果签署了主动服务协议，将发动机信息同步至salesforce
                    asyncCrmService.syncServiceAgreementAndEngineToCRM(userT, esn, true, true);
                    //同步esn给cip
                    List<String> esnList = new ArrayList<>();
                    esnList.add(esn);
                    CipApiUtils.getCipServiceApi().synchronizationEsn(ActionEnum.ADD.getValue(), esnList,null);
                }
                //月度报告
                String vinStr = MapUtils.getString(map, "VIN", "");
                syncEsnAndUserId.asSyncEsnAndUserIdAddOne(esn, vinStr, userT.getId(),null,"1","","");
                //同步老友汇车辆
                externalDataSynchroService.pushLyhEsn(userT.getId(), esn, vinStr, "ADD");
                ParameterTool.writeSuccessResponse(response);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 用户修改设备信息接口
     */
    @Override
    @Transactional
    public ModelAndView updateCustomerEngineRel(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        try {
            UserT userT = UserThreadLocal.get();
            map.put("userId", userT.getId());
            String realCurrentTime = LocalTimeUtil.getRealCurrentTime();
            map.put("UpdateTime", realCurrentTime);

            Long id = MapUtils.getLong(map, "ID", 0L);
            CustomerEngineRelT customerEngineRelT = customerEngineRelDao.getCustomerEngineRelById(id);
            if (null != customerEngineRelT) {
                // 修改发动机信息表
                Map<String, Object> engineMsgMap = new HashMap<>();
                engineMsgMap.put("id", customerEngineRelT.getEngineMsgId());
                EngineMsg engineMsg = engineMsgDao.getEngineMsgById(customerEngineRelT.getEngineMsgId());
                String smn = MapUtils.getString(map,"SMNName","");
                if(null != engineMsg){
                    if(StringUtils.isEmpty(smn) && StringUtils.isEmpty(engineMsg.getSMN())){
                        EngineMasterData engineMasterData = engineMasterDataMapper.selectByesn(engineMsg.getESN());
                        if(null != engineMasterData){
                            smn = engineMasterData.getServiceModelName();
                        }
                        if(StringUtils.isEmpty(smn)) {
                            Map<String, Object> getSMNBySibel = workOrderTServiceImpl.getSMNBySibel(request, engineMsg.getESN());
                            if (MapUtils.isNotEmpty(getSMNBySibel)) {
                                Map<String, Object> data = (Map<String, Object>) MapUtils.getMap(getSMNBySibel, "data");
                                smn = MapUtils.getString(data, "SMN", "");
                            }
                        }
                    }
                }

                if(StringUtils.isNotEmpty(smn)){
                    engineMsgMap.put("SMN", smn);
                }
                if(StringUtils.isBlank(MapUtils.getString(map,"VIN"))){
                    map.put("VIN", customerEngineRelT.getEsn());
                    engineMsgMap.put("equipmentNo",engineMsg.getEquipmentNo());
                } else {
                    engineMsgMap.put("equipmentNo", MapUtils.getString(map,"VIN"));
                }
                //engineMsgMap.put("SMN", smn);
                engineMsgMap.put("vehicleCompany", MapUtils.getString(map,"OEMName"));
                engineMsgMap.put("engineType", MapUtils.getString(map,"engineType"));
                //engineMsgMap.put("manufactor", ""); //未传输
                engineMsgMap.put("serviceChannel", MapUtils.getString(map,"serviceChannel"));
                //engineMsgMap.put("saleDate", ""); //未传输
                engineMsgMap.put("marketType", MapUtils.getString(map,"marketType"));
                engineMsgMap.put("application", MapUtils.getString(map,"application"));
                engineMsgMap.put("warrantyStartDate", MapUtils.getString(map,"warrantyStartDate"));
                engineMsgMap.put("shoppingDate", MapUtils.getString(map, "shoppingDate"));
                if ("CCEC".equals(MapUtils.getString(map, "serviceChannel", ""))) {
                    engineMsgMap.put("series", MapUtils.getString(map, "series"));
                    engineMsgMap.put("estimateWarrantyStartDate", MapUtils.getString(map, "estimateWarrantyStartDate"));
                    engineMsgMap.put("soNo", MapUtils.getString(map, "soNo"));
                    engineMsgMap.put("isWarrantyStart", MapUtils.getIntValue(map, "isWarrantyStart", 2));
                }
                engineMsgDao.updateEngineMsg(engineMsgMap);

                //修改用户和设备关联表
                customerEngineRelDao.updateCustomerEngineRel(map);
                //月度报告 修改 车牌号
                String vinStr = MapUtils.getString(map, "VIN", "");
                syncEsnAndUserId.asSyncEsnAndUserIdUpdateOne(customerEngineRelT.getEsn(), vinStr, userT.getId(),null, customerEngineRelT.getServiceChannel(),customerEngineRelT.getInviteCode(),customerEngineRelT.getSalesChannel());
                //同步老友汇车辆
                externalDataSynchroService.pushLyhEsn(userT.getId(), customerEngineRelT.getEsn(), vinStr, "UPDATE");
            }
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 用户删除设备信息接口
     */
    @Override
    @Transactional
    public ModelAndView deleteCustomerEngineRel(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        map.put("userId", userT.getId());
        Long id = MapUtils.getLong(map, "ID", 0L);
        CustomerEngineRelT customerEngineRelT = customerEngineRelDao.getCustomerEngineRelById(id);
        if (null != customerEngineRelT) {
            // 获取实际当前时间(服务器时间加8小时)
            String realCurrentTime = LocalTimeUtil.getRealCurrentTime();
            map.put("DeleteTime", realCurrentTime);
            customerEngineRelDao.deleteCustomerEngineRel(map);
            //调用公共方法
            userDeleteOrUnBindAuthPublicMethod(customerEngineRelT, userT, realCurrentTime, map);
            //兼容dcec的amt  如果在dcec创建了esn和amt的设备，在其他渠道删除esn时，应该将用户绑定amt表中的数据删除
            CustomerAmtRel customerAmtRel = new CustomerAmtRel();
            customerAmtRel.setFlag(-1);
            customerAmtRel.setCustomerEngineRelId(customerEngineRelT.getId());
            customerAmtRel.setDeleter(userT.getId());
            customerAmtRel.setDeleteTime(LocalTimeUtil.getRealCurrentTime());
            customerAmtRel.setUpdator(userT.getId());
            customerAmtRel.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
            customerAmtRelMapper.updateDeleteByCustomerEngineRelId(customerAmtRel);
        }
        ParameterTool.writeSuccessResponse(response);
        return null;
    }

    //用户删除设备和用户被解除设备授权的公共方法
    private void userDeleteOrUnBindAuthPublicMethod(CustomerEngineRelT customerEngineRelT, UserT userT, String realCurrentTime, Map<String, Object> map) {
        log.info(userT.getId() + "进入到用户删除设备和用户被解除设备授权的公共方法");
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        String headerType = request.getHeader("type");
        int dataSource = StringUtils.isNotBlank(headerType) && headerType.equals("1") ? 3 : 2;
        //sprint55  用户删除设备  同时需要判断当前用户名下是否存在车队，如果存在车队需要将车队下当前设备也删除
        if (StringUtils.isNotEmpty(customerEngineRelT.getEsn())) {
            cipVehicleMapper.updateCipVehicleFlag(userT.getId(), realCurrentTime, customerEngineRelT.getEsn());

            //绑车数据至芯管家后台
            if (StringUtils.isNotBlank(customerEngineRelT.getBusinessNo())) {
                FleetAndEsnRelationRequest xgjRequest = new FleetAndEsnRelationRequest();
                xgjRequest.setEsn(customerEngineRelT.getEsn());
                xgjRequest.setPlatenum(customerEngineRelT.getVin());
                xgjRequest.setDataSource(dataSource);
                xgjRequest.setBusinessNo(customerEngineRelT.getBusinessNo());
                xgjRequest.setOperate("D");
                xgjRequest.setUserId(userT.getId());
                CipApiUtils.getCipServiceApi().syncBindVehicle(xgjRequest,userT.getId());
            }

            //同步esn给cip
            int count = customerEngineRelDao.getCountByUserIdAndEsn(userT.getId(),customerEngineRelT.getEsn());
            if(count <= 0){
                List<String> esnList = new ArrayList<>();
                esnList.add(customerEngineRelT.getEsn());
                CipApiUtils.getCipServiceApi().synchronizationEsn(ActionEnum.DELLETE.getValue(), esnList,customerEngineRelT.getBusinessNo());
            }
        }

        Long count = saDao.isSignAgreement(userT.getId(), LocalTimeUtil.getRealCurrentTime());
        if (count > 0) {//用户如果签署了主动服务协议，将发动机信息同步至salesforce
            asyncCrmService.syncServiceAgreementAndEngineToCRM(userT, customerEngineRelT.getEsn(), true, false);
        }
        //月度报告实时更新ESN  同步给春卷团队
        syncEsnAndUserId.asSyncEsnAndUserIdDelOne(customerEngineRelT.getEsn(), userT.getId());
        //同步老友汇车辆
        externalDataSynchroService.pushLyhEsn(userT.getId(), customerEngineRelT.getEsn(), customerEngineRelT.getVin(), "DEL");
        // sprint 57  删除设备时，将油耗计算器正在进行中的测量关闭
        this.syncFuelMeasure(customerEngineRelT.getEsn(), customerEngineRelT.getUserId(), request);
    }


    /**
     * 根据用户id获取大运设备列表
     */
    @Override
    public ModelAndView getDYCustomerEngineRel(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        String keyword = MapUtils.getString(map,"keyword");
        Map<String,Object> queryMap = new HashMap<>(2);
        queryMap.put("userId",userT.getId());
        queryMap.put("keyword",keyword);
        List<Map<String, Object>> customerEngineRelList = customerEngineRelDao.getDYCustomerEngineRelList(queryMap);
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(customerEngineRelList)) {
            for (Map<String, Object> dataMap : customerEngineRelList) {
                Map<String, Object> subData = new HashMap<>();
                subData.put("ID", MapUtils.getLong(dataMap, "ID"));
                subData.put("EngineMsgId", MapUtils.getLong(dataMap, "id"));
                subData.put("ESN", MapUtils.getString(dataMap, "ESN"));
                subData.put("SMN", MapUtils.getString(dataMap, "SMN", ""));
                subData.put("VIN", MapUtils.getString(dataMap, "equipmentNo", ""));
                subData.put("OEMID", 0L);
                subData.put("OEMName", MapUtils.getString(dataMap, "vehicleCompany", ""));
                subData.put("EngineType", MapUtils.getString(dataMap, "engineType", ""));
                subData.put("WarrantyStartDate", MapUtils.getString(dataMap, "WarrantyStartDate", ""));
                subData.put("Application", MapUtils.getString(dataMap, "Application", ""));
                subData.put("MarketType", MapUtils.getString(dataMap, "MarketType", ""));
                subData.put("ShoppingDate", MapUtils.getString(dataMap, "ShoppingDate", ""));
                dataList.add(subData);
            }
        }
        Map<String, Object> data = new HashMap<>(1);
        data.put("customerEngineRelList", dataList);
        ParameterTool.writeSuccessResponse(response, data);
        return null;
    }



    /**
     * 用户添加设备信息接口   因一键登录需求改版了用户绑定设备逻辑  统一绑定设备界面，为兼容新老用户这里新开发添加设备接口
     */
    @Override
    @Transactional
    public ModelAndView newAddCustomerEngineRel(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String paramStr = MapUtils.getString(map,"paramStr","");
        if(StringUtils.isEmpty(paramStr)){
            ParameterTool.writeResponse(response, 17,"缺少必要参数！");
            return null;
        }
        log.info("newAddCustomerEngineRel.aspx接口入参paramStr："+paramStr);
        Map<String,Object> paramMap = JSON.parseObject(paramStr, Map.class);
        try {
            UserT userT = UserThreadLocal.get();
            paramMap.put("UserId", userT.getId());
            paramMap.put("Phone", userT.getPhone());
            paramMap.put("Creator", userT.getId());
            // 获取实际当前时间(服务器时间加8小时)
            paramMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());

            // 验证ESN是否重复
            String esn = MapUtils.getString(paramMap, "ESN", "");
            String vin = MapUtils.getString(paramMap, "VIN", "");
            int equipmentTypeIntValue = MapUtils.getIntValue(paramMap, "EquipmentType", -1);
            if (StringUtils.isEmpty(esn) || StringUtils.isEmpty(vin) || equipmentTypeIntValue == -1) {
                ParameterTool.writeResponse(response, 17, "缺少必要参数！");
                return null;
            }
            //验证是否签署了主动服务协议
            ServiceAgreement serviceAggrementDetail = serviceAgrementDao.getServiceAggrementDetail(userT.getId(), 0);
            if (Objects.isNull(serviceAggrementDetail)) {
                ParameterTool.writeResponse(response, -99, "请签署主动服务协议！");
                return null;
            }
            int num = customerEngineRelDao.getRelationByUserIdAndESN(userT.getId(), esn);
            if (num > 0) {
                ParameterTool.writeErrorResponse(response, -15);
            } else if (!this.esnByCheck(esn)) {
                ParameterTool.writeErrorResponse(response, -46);
            } else {
                //验证 movexID
                String businessNo = MapUtils.getString(paramMap, "BusinessNo", "");

                EngineMsg engineMsg = engineMsgDao.getEngineMsgByESNString(esn);
                //调用cip接口获取esn信息
                EsnBasicInfoEntity esnInfo = null;
                EngineMasterData engineMasterData = engineMasterDataMapper.selectByesn(esn);
                if(null != engineMasterData){
                    esnInfo = new EsnBasicInfoEntity();
                    esnInfo.setServiceModelName(engineMasterData.getServiceModelName());
                    esnInfo.setEmissionLevel(engineMasterData.getRelBulletinTelAboEmissionLevel());
                    esnInfo.setFuelType(engineMasterData.getEngineFuelType());
                    esnInfo.setVin(engineMasterData.getBulletinTelVin());
                } else {
                    CipResponeEntity respone = CipApiUtils.getCipServiceApi().getEsnInfo(esn);
                    if (null != respone) {
                        map.put("cipReturnValue", JSON.toJSON(respone).toString());
                        if (respone.getCode().equals(0)) {
                            esnInfo = (EsnBasicInfoEntity) JSONObject.toBean(respone.getData(), EsnBasicInfoEntity.class);
                        }
                    }
                }
                Map<String, Object> engineMsgMap = new HashMap<>();
                int fleetEmissionLevelDInt = -1;
                int fleetFuelTypeDInt = -1;
                //设置排放信息
                if(null != esnInfo){
                    String emissionLevel =  esnInfo.getEmissionLevel();
                    String fuelType = esnInfo.getFuelType();
                    //获取字典表应用类型map(调用cip接口返回的应用类型枚举值)
                    Map<String,Map<String,Object>> fleetEmissionLevelDicListMap = dictionariesTDao.getDicListByDtableName("fleetEmissionLevel");
                    if(MapUtils.isNotEmpty(fleetEmissionLevelDicListMap) && StringUtils.isNotEmpty(emissionLevel) && fleetEmissionLevelDicListMap.containsKey(emissionLevel)){
                        Map<String,Object> fleetEmissionLevelDicMap = MapUtils.getObject(fleetEmissionLevelDicListMap,emissionLevel);
                        if(MapUtils.isNotEmpty(fleetEmissionLevelDicMap)){
                            fleetEmissionLevelDInt = MapUtils.getIntValue(fleetEmissionLevelDicMap,"DInt",-1);
                        }
                    }
                    //获取字典表动力类型ma(调用cip接口返回的应用类型枚举值)
                    Map<String,Map<String,Object>> fleetFuelTypeDicListMap = dictionariesTDao.getDicListByDtableName("fleetFuelType");
                    if(MapUtils.isNotEmpty(fleetFuelTypeDicListMap) && StringUtils.isNotEmpty(fuelType) && fleetFuelTypeDicListMap.containsKey(fuelType)){
                        Map<String,Object> fleetFuelTypeDicMap = MapUtils.getObject(fleetFuelTypeDicListMap,fuelType);
                        if(MapUtils.isNotEmpty(fleetFuelTypeDicMap)){
                            fleetFuelTypeDInt = MapUtils.getIntValue(fleetFuelTypeDicMap,"DInt",-1);
                        }
                    }
                    engineMsgMap.put("model",emissionLevel);
                }
                engineMsgMap.put("EsnApplicationType",fleetEmissionLevelDInt);
                engineMsgMap.put("EsnPowerType",fleetFuelTypeDInt);
                String smn = MapUtils.getString(paramMap,"SMNName","");
                if(null == engineMsg){
                    engineMsgMap.put("ESN", MapUtils.getString(paramMap,"ESN"));
                    if(StringUtils.isEmpty(smn)){  //如果前端传的smn是空的   调用sibel接口
                        if(null != esnInfo && StringUtils.isNotBlank(esnInfo.getServiceModelName())){
                            smn =  esnInfo.getServiceModelName();
                        }
                        if(StringUtils.isEmpty(smn)){
                            Map<String,Object> getSMNBySibel = workOrderTServiceImpl.getSMNBySibel(request,esn);
                            if(MapUtils.isNotEmpty(getSMNBySibel)){
                                Map<String, Object> data = (Map<String, Object>) MapUtils.getMap(getSMNBySibel, "data");
                                smn =  MapUtils.getString(data, "SMN","");
                            }
                        }
                    }
                    if(StringUtils.isNotEmpty(smn)){
                        engineMsgMap.put("SMN", smn);
                        paramMap.put("SMNName",smn);
                    }
                    engineMsgMap.put("equipmentNo", vin);
                    engineMsgMap.put("vehicleCompany", MapUtils.getString(paramMap,"OEMName"));
                    //保存发动机信息
                    engineMsgDao.newInsertEngineMsg(engineMsgMap);
                    //将新插入发动机信息ID放入关联表中
                    paramMap.put("EngineMsgId", MapUtils.getLong(engineMsgMap, "id"));
                }else{
                    if(StringUtils.isEmpty(smn) && StringUtils.isEmpty(engineMsg.getSMN())){
                        if(null != esnInfo && StringUtils.isNotBlank(esnInfo.getServiceModelName())){
                            smn =  esnInfo.getServiceModelName();
                        }
                        if(StringUtils.isEmpty(smn)){
                            Map<String, Object> getSMNBySibel = workOrderTServiceImpl.getSMNBySibel(request, esn);
                            if (MapUtils.isNotEmpty(getSMNBySibel)) {
                                Map<String, Object> data = (Map<String, Object>) MapUtils.getMap(getSMNBySibel, "data");
                                smn = MapUtils.getString(data, "SMN", "");
                            }
                        }
                    }
                    if(StringUtils.isNotEmpty(smn)){
                        engineMsgMap.put("SMN", smn);
                        paramMap.put("SMNName",smn);
                    }
                    engineMsgMap.put("equipmentNo", vin);
                    engineMsgMap.put("vehicleCompany", MapUtils.getString(paramMap,"OEMName"));
                    engineMsgMap.put("id", engineMsg.getId());
                    if(null == esnInfo){
                        engineMsgMap.put("model", engineMsg.getModel());
                    }
                    engineMsgDao.updateEngineMsg(engineMsgMap);
                    paramMap.put("EngineMsgId", engineMsg.getId());
                }
                //活动绑车拉新
                //获取活动信息 活动期间报的问题
                ActivityT activity = inviteDao.getActivity(INVITE);
                if(null != activity && activity.getIsOpen().equals(1)
                        && StringUtils.isNotEmpty(activity.getEndTime())
                        && LocalTimeUtil.isBefore(LocalTimeUtil.getRealCurrentTime(),activity.getEndTime())){
                    int bindAddStatus = 0;
                    if (null != esnInfo) {
                        bindAddStatus = inviteUserService.addBind(esn, esnInfo.getEmissionLevel());
                    } else {
                        bindAddStatus = BindAddMessageStatus.BAOCUO.getStatus();
                    }
                    paramMap.put("bindAddStatus", bindAddStatus);
                    paramMap.put("bindAddMessage", BindAddMessageStatus.getDescByCode(bindAddStatus));
                }
                //百万圆桌绑车
                inviteUserService.addBwyzBind(esn, userT.getId());
                //首次绑车添加蜜值
                int customerEngineRelTCount = customerEngineRelDao.getCountByUserId(userT.getId());
                if (customerEngineRelTCount <= 0) {
                    //同步添加蜜值的方法
                    syncAddhoney(request);
                }
                //添加用户引流渠道为 设备归属
                ConductionInfo conductionInfo = userTDao.getConductionByUserId(userT.getId());
                paramMap.put("salesChannel", null != conductionInfo ? conductionInfo.getChannel() : "");
                customerEngineRelDao.newAddCustomerEngineRel(paramMap);
                //保存ocr的数据
                if (paramMap.containsKey("OcrVehicleLicense")) {
                    //CustomerEngineId
                    String ocrVehicleLicenseStr = MapUtils.getString(paramMap, "OcrVehicleLicense", "");
                    if (StringUtils.isNotBlank(ocrVehicleLicenseStr)) {
                        Map<String,Object> ocrDrivingLicenseMap = JSON.parseObject(ocrVehicleLicenseStr, Map.class);
                        ocrDrivingLicenseMap.put("CustomerEngineId",paramMap.get("id"));
                        ocrDrivingLicenseMap.put("Flag",0);
                        ocrDrivingLicenseMap.put("Creator", userT.getId());
                        // 获取实际当前时间(服务器时间加8小时)
                        ocrDrivingLicenseMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
                        ocrVehicleLicenseTMapper.insertSelective(ocrDrivingLicenseMap);
                    }
                }
                Long count = saDao.isSignAgreement(userT.getId(), LocalTimeUtil.getRealCurrentTime());
                if (count > 0) {//用户如果签署了主动服务协议，将发动机信息同步至salesforce
                    asyncCrmService.syncServiceAgreementAndEngineToCRM(userT, esn, true, true);
                    //同步esn给cip
                    List<String> esnList = new ArrayList<>();
                    esnList.add(esn);
                    CipApiUtils.getCipServiceApi().synchronizationEsn(ActionEnum.ADD.getValue(), esnList,businessNo);
                }
                //月度报告实时更新ESN  同步给春卷团队
                String vinStr = MapUtils.getString(paramMap, "VIN", "");

                syncEsnAndUserId.asSyncEsnAndUserIdAddOne(esn, vinStr, userT.getId(),MapUtils.getString(paramMap,"DrivingLicensePhotoUrl"),MapUtils.getString(paramMap,"ServiceChannel",""),MapUtils.getString(paramMap,"InviteCode",""),MapUtils.getString(paramMap,"salesChannel",""));
                //同步老友汇车辆
                externalDataSynchroService.pushLyhEsn(userT.getId(), esn, vinStr, "ADD");
                //绑车数据至芯管家后台
                if (StringUtils.isNotBlank(businessNo)) {
                    ServiceStationT serviceStationT = serviceStationDaoMapper.getStationByStationNo(businessNo);
                    if (null != serviceStationT) {
                        List<String> stationNameList = xgjGetUserInfoMapper.getVehicleListByEsn(esn, serviceStationT.getStationno());
                        String headerType = request.getHeader("type");
                        int dataSource = StringUtils.isNotBlank(headerType) && headerType.equals("1") ? 3 : 2;
                        FleetAndEsnRelationRequest xgjRequest = new FleetAndEsnRelationRequest();
                        xgjRequest.setEsn(esn);
                        xgjRequest.setPlatenum(vin);
                        xgjRequest.setBusinessNo(businessNo);
                        xgjRequest.setDataSource(dataSource);
                        if (CollectionUtils.isNotEmpty(stationNameList)) {
                            xgjRequest.setOperate("U");
                        } else {
                            xgjRequest.setOperate("I");
                        }
                        xgjRequest.setVehicleType(fleetEmissionLevelDInt == 0 ? 1 : 2);
                        String ocrVIN = MapUtils.getString(paramMap, "NewVIN", "");
                        String cipvin = StringUtils.isBlank(ocrVIN) ? null != esnInfo ? esnInfo.getVin() : "" : ocrVIN;
                        xgjRequest.setVin(cipvin);
                        xgjRequest.setUserId(userT.getId());
                        CipApiUtils.getCipServiceApi().syncBindVehicle(xgjRequest, userT.getId());
                    }
                }
                //绑车完成新手活动
                cipServiceApi.finishNeophyteTaskUser("bindVehicle","绑定esn：" + esn,request.getHeader("userid"),request.getHeader("Authorization"));
                Map<String, Object> vipMap = customerEngineRelDao.getVIPTypeByUserIdAndEsn(userT.getId(),esn);
                Integer vipType = MapUtils.getInteger(vipMap,"vipType");
                if(null == vipType){
                    vipType = 0;
                } else if(vipType == 1 || vipType == 5|| vipType == 7){
                    vipType = 1;
                }
                EngineMasterData  engineData = engineMasterDataMapper.selectByesn(esn);
                int inBlackList = 0;
                if(null != engineData && StringUtils.isNotBlank(engineData.getInBlackList()) && engineData.getInBlackList().equals("1")){
                    inBlackList = 1;
                }
                int inConnectivity = 0;
                if(null != engineData && StringUtils.isNotBlank(engineData.getInConnectivity()) && engineData.getInConnectivity().equals("1")){
                    inConnectivity = 1;
                }
                paramMap.put("inConnectivity",1);
                paramMap.put("inBlackList",0);

                paramMap.put("VipType",vipType);
                paramMap.put("ExpirationTime",MapUtils.getString(vipMap,"expirationTime",""));
                paramMap.put("EsnApplicationType",fleetEmissionLevelDInt);
                paramMap.put("EsnPowerType",fleetFuelTypeDInt);
                ParameterTool.writeSuccessResponse(response,paramMap);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * wa 自动绑车的接口
     *
     * @param map
     * @return
     */
    @Override
    @Transactional
    public ModelAndView waNewAddCustomerEngineRel(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String esn = MapUtils.getString(map, "ESN", "");
        if (StringUtils.isEmpty(esn)) {
            ParameterTool.writeResponse(response, 17, "缺少必要参数！");
            return null;
        }
        Map<String, Object> paramMap = new HashMap<>();
        try {
            paramMap.put("ESN", esn);
            UserT userT = UserThreadLocal.get();
            paramMap.put("UserId", userT.getId());
            paramMap.put("Phone", userT.getPhone());
            paramMap.put("Creator", userT.getId());
            // 获取实际当前时间(服务器时间加8小时)
            paramMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
            paramMap.put("VIN", esn);
            int num = customerEngineRelDao.getRelationByUserIdAndESN(userT.getId(), esn);
            if (num > 0) {
                ParameterTool.writeErrorResponse(response, -15);
            } else {
                EngineMsg engineMsg = engineMsgDao.getEngineMsgByESNString(esn);
                Map<String, Object> engineMsgMap = new HashMap<>();
                //先查询cip的esn主数据表
                String emissionLevel = null;
                int fleetEmissionLevelDInt = -1;
                Map<String, Map<String, Object>> fleetEmissionLevelDicListMap = dictionariesTDao.getDicListByDtableName("fleetEmissionLevel");

                EngineMasterData engineMasterData = engineMasterDataMapper.selectByesn(esn);
                if (null != engineMasterData) {
                    String fuelType = engineMasterData.getEngineFuelType();
                    emissionLevel = engineMasterData.getRelBulletinTelAboEmissionLevel();
                    if (MapUtils.isNotEmpty(fleetEmissionLevelDicListMap) && StringUtils.isNotEmpty(emissionLevel) && fleetEmissionLevelDicListMap.containsKey(emissionLevel)) {
                        Map<String, Object> fleetEmissionLevelDicMap = MapUtils.getObject(fleetEmissionLevelDicListMap, emissionLevel);
                        if (MapUtils.isNotEmpty(fleetEmissionLevelDicMap)) {
                            fleetEmissionLevelDInt = MapUtils.getIntValue(fleetEmissionLevelDicMap, "DInt", -1);
                        }
                    }
                    //将esn 中的 应用类型  和 动力类型 赋值
                    this.putEngine(fleetEmissionLevelDInt, fuelType, engineMsgMap);
                    if (fleetEmissionLevelDInt == 0) {
                        paramMap.put("NewVIN", engineMasterData.getBulletinTelVin());
                    }
                } else {
                    //调用cip接口获取esn信息
                    EsnBasicInfoEntity esnInfo = null;
                    CipResponeEntity respone = CipApiUtils.getCipServiceApi().getEsnInfo(esn);
                    if (null != respone) {
                        map.put("cipReturnValue", JSON.toJSON(respone).toString());
                        if (respone.getCode().equals(0)) {
                            esnInfo = (EsnBasicInfoEntity) JSONObject.toBean(respone.getData(), EsnBasicInfoEntity.class);
                        }
                    }
                    //设置排放信息
                    if (null != esnInfo) {
                        emissionLevel = esnInfo.getEmissionLevel();
                        String fuelType = esnInfo.getFuelType();
                        if (MapUtils.isNotEmpty(fleetEmissionLevelDicListMap) && StringUtils.isNotEmpty(emissionLevel) && fleetEmissionLevelDicListMap.containsKey(emissionLevel)) {
                            Map<String, Object> fleetEmissionLevelDicMap = MapUtils.getObject(fleetEmissionLevelDicListMap, emissionLevel);
                            if (MapUtils.isNotEmpty(fleetEmissionLevelDicMap)) {
                                fleetEmissionLevelDInt = MapUtils.getIntValue(fleetEmissionLevelDicMap, "DInt", -1);
                            }
                        }
                        //将esn 中的 动力类型  和 应用类型 赋值
                        this.putEngine(fleetEmissionLevelDInt, fuelType, engineMsgMap);
                        if (fleetEmissionLevelDInt == 0) {
                            paramMap.put("NewVIN", esnInfo.getVin());
                        }
                    }
                }
                String smn = MapUtils.getString(paramMap, "SMNName", "");
                if (null == engineMsg) {
                    engineMsgMap.put("ESN", MapUtils.getString(paramMap, "ESN"));
                    if (StringUtils.isEmpty(smn)) {  //如果前端传的smn是空的   调用sibel接口
                        if(null != engineMasterData){
                            smn = engineMasterData.getServiceModelName();
                        }
                        if(StringUtils.isEmpty(smn)) {
                            Map<String, Object> getSMNBySibel = workOrderTServiceImpl.getSMNBySibel(request, esn);
                            if (MapUtils.isNotEmpty(getSMNBySibel)) {
                                Map<String, Object> data = (Map<String, Object>) MapUtils.getMap(getSMNBySibel, "data");
                                smn = MapUtils.getString(data, "SMN", "");
                            }
                        }
                    }
                    if (StringUtils.isNotEmpty(smn)) {
                        engineMsgMap.put("SMNName", smn);
                        paramMap.put("SMNName", smn);
                    }
                    engineMsgMap.put("equipmentNo", esn);
                    engineMsgMap.put("vehicleCompany", MapUtils.getString(paramMap, "OEMName"));
                    //保存发动机信息
                    engineMsgDao.newInsertEngineMsg(engineMsgMap);
                    //将新插入发动机信息ID放入关联表中
                    paramMap.put("EngineMsgId", MapUtils.getLong(engineMsgMap, "id"));
                } else {
                    paramMap.put("EngineMsgId", engineMsg.getId());
                }
                //获取活动信息 活动期间报的问题
                ActivityT activity = inviteDao.getActivity(INVITE);
                if (null != activity && activity.getIsOpen().equals(1)
                        && StringUtils.isNotEmpty(activity.getEndTime())
                        && LocalTimeUtil.isBefore(LocalTimeUtil.getRealCurrentTime(), activity.getEndTime())) {
                    int bindAddStatus = 0;
                    if (StringUtils.isNotBlank(emissionLevel)) {
                        bindAddStatus = inviteUserService.addBind(esn, emissionLevel);
                    } else {
                        bindAddStatus = BindAddMessageStatus.BAOCUO.getStatus();
                    }
                    paramMap.put("bindAddStatus", bindAddStatus);
                    paramMap.put("bindAddMessage", BindAddMessageStatus.getDescByCode(bindAddStatus));
                }
                //百万圆桌绑车
                inviteUserService.addBwyzBind(esn, userT.getId());
                //首次绑车添加蜜值
                int customerEngineRelTCount = customerEngineRelDao.getCountByUserId(userT.getId());
                if (customerEngineRelTCount <= 0) {
                    //同步添加蜜值的方法
                    syncAddhoney(request);
                }
                String businessNo = userTDao.getBusinessByUserId(userT.getId());
                paramMap.put("BusinessNo", businessNo);
                customerEngineRelDao.newAddCustomerEngineRel(paramMap);
                Long count = saDao.isSignAgreement(userT.getId(), LocalTimeUtil.getRealCurrentTime());
                if (count > 0) {//用户如果签署了主动服务协议，将发动机信息同步至salesforce
                    asyncCrmService.syncServiceAgreementAndEngineToCRM(userT, esn, true, true);
                    //同步esn给cip
                    List<String> esnList = new ArrayList<>();
                    esnList.add(esn);
                    CipApiUtils.getCipServiceApi().synchronizationEsn(ActionEnum.ADD.getValue(), esnList,null);
                }
                //月度报告实时更新ESN  同步给春卷团队
                String vinStr = MapUtils.getString(paramMap, "VIN", "");
                syncEsnAndUserId.asSyncEsnAndUserIdAddOne(esn, vinStr, userT.getId(),MapUtils.getString(paramMap,"DrivingLicensePhotoUrl"),MapUtils.getString(paramMap,"ServiceChannel",""),MapUtils.getString(paramMap,"InviteCode",""),MapUtils.getString(paramMap,"salesChannel",""));
                //同步老友汇车辆
                externalDataSynchroService.pushLyhEsn(userT.getId(), esn, vinStr, "ADD");
                //绑车完成新手活动
                cipServiceApi.finishNeophyteTaskUser("bindVehicle","绑定esn：" + esn,request.getHeader("userid"),request.getHeader("Authorization"));
                //绑车数据至芯管家后台
                if (StringUtils.isNotBlank(businessNo)) {
                    ServiceStationT serviceStationT = serviceStationDaoMapper.getStationByStationNo(businessNo);
                    if (null != serviceStationT) {
                        List<String> stationNameList = xgjGetUserInfoMapper.getVehicleListByEsn(esn, serviceStationT.getStationno());
                        String headerType = request.getHeader("type");
                        int dataSource = StringUtils.isNotBlank(headerType) && headerType.equals("1") ? 3 : 2;
                        FleetAndEsnRelationRequest xgjRequest = new FleetAndEsnRelationRequest();
                        xgjRequest.setEsn(esn);
                        xgjRequest.setPlatenum(vinStr);
                        xgjRequest.setBusinessNo(businessNo);
                        xgjRequest.setDataSource(dataSource);
                        if (CollectionUtils.isNotEmpty(stationNameList)) {
                            xgjRequest.setOperate("U");
                        } else {
                            xgjRequest.setOperate("I");
                        }
                        xgjRequest.setVehicleType(fleetEmissionLevelDInt == 0 ? 1 : 2);
                        String ocrVIN = MapUtils.getString(paramMap, "NewVIN", "");
                        String cipvin = ocrVIN;
                        xgjRequest.setVin(cipvin);
                        xgjRequest.setUserId(userT.getId());
                        CipApiUtils.getCipServiceApi().syncBindVehicle(xgjRequest, userT.getId());
                    }
                }
                ParameterTool.writeSuccessResponse(response);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 将esn 中的 应用类型 和  动力类型 赋值
     *
     * @param emissionLevel
     * @param fuelType
     * @param engineMsgMap
     */
    public void putEngine(int emissionLevel, String fuelType, Map<String, Object> engineMsgMap) {
        int fleetEmissionLevelDInt = -1;
        int fleetFuelTypeDInt = -1;
//        //获取字典表应用类型map(调用cip接口返回的应用类型枚举值)
//        Map<String, Map<String, Object>> fleetEmissionLevelDicListMap = dictionariesTDao.getDicListByDtableName("fleetEmissionLevel");
//        if (MapUtils.isNotEmpty(fleetEmissionLevelDicListMap) && StringUtils.isNotEmpty(emissionLevel) && fleetEmissionLevelDicListMap.containsKey(emissionLevel)) {
//            Map<String, Object> fleetEmissionLevelDicMap = MapUtils.getObject(fleetEmissionLevelDicListMap, emissionLevel);
//            if (MapUtils.isNotEmpty(fleetEmissionLevelDicMap)) {
//                fleetEmissionLevelDInt = MapUtils.getIntValue(fleetEmissionLevelDicMap, "DInt", -1);
//            }
//        }
        //获取字典表动力类型ma(调用cip接口返回的应用类型枚举值)
        Map<String, Map<String, Object>> fleetFuelTypeDicListMap = dictionariesTDao.getDicListByDtableName("fleetFuelType");
        if (MapUtils.isNotEmpty(fleetFuelTypeDicListMap) && StringUtils.isNotEmpty(fuelType) && fleetFuelTypeDicListMap.containsKey(fuelType)) {
            Map<String, Object> fleetFuelTypeDicMap = MapUtils.getObject(fleetFuelTypeDicListMap, fuelType);
            if (MapUtils.isNotEmpty(fleetFuelTypeDicMap)) {
                fleetFuelTypeDInt = MapUtils.getIntValue(fleetFuelTypeDicMap, "DInt", -1);
            }
        }
        engineMsgMap.put("model", emissionLevel);
        engineMsgMap.put("EsnApplicationType", fleetEmissionLevelDInt);
        engineMsgMap.put("EsnPowerType", fleetFuelTypeDInt);
    }

    /**
     * 用户修改设备信息接口   因一键登录需求改版了用户绑定设备逻辑  统一绑定设备界面，为兼容新老用户这里新开发修改设备接口
     */
    @Override
    @Transactional
    public ModelAndView newUpdateCustomerEngineRel(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String paramStr = MapUtils.getString(map, "paramStr", "");
        if(StringUtils.isEmpty(paramStr)){
            ParameterTool.writeResponse(response, 17,"缺少必要参数！");
            return null;
        }
        log.info("newUpdateCustomerEngineRel.aspx接口入参paramStr："+paramStr);
        Map<String,Object> paramMap = JSON.parseObject(paramStr, Map.class);
        String esn = MapUtils.getString(paramMap, "ESN", "");
        String vin =  MapUtils.getString(paramMap, "VIN", "");
        int equipmentTypeIntValue = MapUtils.getIntValue(paramMap,"EquipmentType",-1);
        Long customerEngineRelID = MapUtils.getLong(paramMap, "CustomerEngineRelID", -1L);
        if(StringUtils.isEmpty(esn) || StringUtils.isEmpty(vin) || equipmentTypeIntValue == -1 || customerEngineRelID == -1){
            ParameterTool.writeResponse(response, 17,"缺少必要参数！");
            return null;
        }
        try {
            //验证 movexID
            String businessNo = MapUtils.getString(paramMap, "BusinessNo", "");

            UserT userT = UserThreadLocal.get();
            paramMap.put("UserId", userT.getId());
            String realCurrentTime = LocalTimeUtil.getRealCurrentTime();
            paramMap.put("Updator", userT.getId());
            paramMap.put("UpdateTime", realCurrentTime);

            CustomerEngineRelT customerEngineRelT = customerEngineRelDao.getCustomerEngineRelById(customerEngineRelID);
            if (null != customerEngineRelT) {
                EngineMasterData engineMasterData = engineMasterDataMapper.selectByesn(esn);
                // 修改发动机信息表
                Map<String, Object> engineMsgMap = new HashMap<>();
                engineMsgMap.put("id", customerEngineRelT.getEngineMsgId());
                EngineMsg engineMsg = engineMsgDao.getEngineMsgById(customerEngineRelT.getEngineMsgId());
                String smn = MapUtils.getString(paramMap,"SMNName","");
                if(null != engineMsg){
                    if(StringUtils.isEmpty(smn) && StringUtils.isNotEmpty(engineMsg.getSMN())){
                        smn = engineMsg.getSMN();
                    }
                    if(StringUtils.isEmpty(smn)){
                        if(null != engineMasterData){
                            smn = engineMasterData.getServiceModelName();
                        }
                        if(StringUtils.isEmpty(smn)){
                            Map<String,Object> getSMNBySibel = workOrderTServiceImpl.getSMNBySibel(request,engineMsg.getESN());
                            if(MapUtils.isNotEmpty(getSMNBySibel)){
                                Map<String, Object> data = (Map<String, Object>) MapUtils.getMap(getSMNBySibel, "data");
                                if(StringUtils.isNotEmpty(MapUtils.getString(data, "SMN",""))){
                                    smn =  MapUtils.getString(data, "SMN","");
                                }
                            }
                        }
                    }
                }
                if (StringUtils.isNotEmpty(smn)) {
                    engineMsgMap.put("SMN", smn);
                    paramMap.put("SMNName", smn);
                }
                engineMsgMap.put("equipmentNo", MapUtils.getString(paramMap, "VIN"));
                engineMsgMap.put("vehicleCompany", MapUtils.getString(paramMap, "OEMName"));
                engineMsgDao.updateEngineMsg(engineMsgMap);
                //修改用户和设备关联表
                //BusinessNoNum   表示用来更新BusinessNo 字段
                paramMap.put("BusinessNoNum", 1);
                //添加用户引流渠道为 设备归属
                ConductionInfo conductionInfo = userTDao.getConductionByUserId(userT.getId());
                paramMap.put("salesChannel", null != conductionInfo ? conductionInfo.getChannel() : "");
                customerEngineRelDao.newUpdateCustomerEngineRel(paramMap);

                //保存ocr的数据
                if (paramMap.containsKey("OcrVehicleLicense")) {
                   // 将之前的额数据删除
                    OcrVehicleLicenseT ocrDrivingLicenseT = new OcrVehicleLicenseT();
                    ocrDrivingLicenseT.setCustomerEngineId(customerEngineRelID);
                    List<OcrVehicleLicenseT> list = ocrVehicleLicenseTMapper.selectList(ocrDrivingLicenseT);
                    for (OcrVehicleLicenseT drivingLicenseT : list) {
                        drivingLicenseT.setFlag(-1);
                        drivingLicenseT.setDeleter(userT.getId());
                        drivingLicenseT.setDeleteTime(LocalTimeUtil.getRealCurrentTime());
                        ocrVehicleLicenseTMapper.updateByPrimaryKeySelective(drivingLicenseT);
                    }
                    //CustomerEngineId
                    String ocrVehicleLicenseStr = MapUtils.getString(paramMap, "OcrVehicleLicense", "");
                    if (StringUtils.isNotBlank(ocrVehicleLicenseStr)) {
                        Map<String,Object> ocrDrivingLicenseMap = JSON.parseObject(ocrVehicleLicenseStr, Map.class);
                        ocrDrivingLicenseMap.put("CustomerEngineId",customerEngineRelT.getId());
                        ocrDrivingLicenseMap.put("Flag",0);
                        ocrDrivingLicenseMap.put("Creator", userT.getId());
                        // 获取实际当前时间(服务器时间加8小时)
                        ocrDrivingLicenseMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
                        ocrVehicleLicenseTMapper.insertSelective(ocrDrivingLicenseMap);
                    }
                }

                //月度报告 修改 车牌号
                String vinStr = MapUtils.getString(paramMap, "VIN", "");
                syncEsnAndUserId.asSyncEsnAndUserIdUpdateOne(customerEngineRelT.getEsn(), vinStr, userT.getId(),MapUtils.getString(paramMap,"DrivingLicensePhotoUrl"),customerEngineRelT.getServiceChannel(),MapUtils.getString(paramMap,"InviteCode",customerEngineRelT.getInviteCode()),MapUtils.getString(paramMap,"salesChannel",customerEngineRelT.getSalesChannel()));
                //同步老友汇车辆
                externalDataSynchroService.pushLyhEsn(userT.getId(), esn, vinStr, "UPDATE");
                //绑车数据至芯管家后台
                if (!(StringUtils.isBlank(businessNo) && StringUtils.isBlank(customerEngineRelT.getBusinessNo()))) {
                    String headerType = request.getHeader("type");
                    int dataSource = StringUtils.isNotBlank(headerType) && headerType.equals("1") ? 3 : 2;
                    FleetAndEsnRelationRequest xgjRequest = new FleetAndEsnRelationRequest();
                    xgjRequest.setEsn(esn);
                    xgjRequest.setPlatenum(vin);
                    xgjRequest.setDataSource(dataSource);
                    xgjRequest.setUserId(userT.getId());
                    xgjRequest.setVehicleType(null != engineMsg &&  null != engineMsg.getEsnApplicationType() && engineMsg.getEsnApplicationType() == 0 ? 1 : 2);
                    String ocrVIN = MapUtils.getString(paramMap, "NewVIN", "");
                    String cipvin = StringUtils.isBlank(ocrVIN) ? null != engineMasterData && null != engineMasterData.getBulletinTelVin() ? engineMasterData.getBulletinTelVin() : "" : ocrVIN;
                    xgjRequest.setVin(cipvin);
                    if(StringUtils.isBlank(businessNo) && StringUtils.isNotBlank(customerEngineRelT.getBusinessNo())){
                        xgjRequest.setBusinessNo(customerEngineRelT.getBusinessNo());
                        xgjRequest.setOperate("D");
                    } else if(StringUtils.isNotBlank(businessNo)){
                        xgjRequest.setBusinessNo(businessNo);
                        ServiceStationT serviceStationT = serviceStationDaoMapper.getStationByStationNo(businessNo);
                        if (null != serviceStationT) {
                            List<String> stationNameList = xgjGetUserInfoMapper.getVehicleListByEsn(esn, serviceStationT.getStationno());
                            if (CollectionUtils.isNotEmpty(stationNameList)) {
                                xgjRequest.setOperate("U");
                            } else {
                                xgjRequest.setOperate("I");
                            }
                        }
                    }
                    CipApiUtils.getCipServiceApi().syncBindVehicle(xgjRequest,userT.getId());
                }
            }
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }
// 添加油耗导航的常用地点
    public void saveRegularLocation(Map<String, Object> paramMap,CustomerEngineRelT relationByUserId) {
        log.error("RegularLocationList1111111:"+paramMap.toString());
        if (paramMap.get("RegularLocationList")!=null) {
            log.error("RegularLocationList:"+paramMap.get("RegularLocationList").toString());

            List<RegularLocation> regularLocationList = com.alibaba.fastjson.JSON.parseArray(paramMap.get("RegularLocationList").toString(), RegularLocation.class);
            if (CollectionUtils.isNotEmpty(regularLocationList)) {
                for (RegularLocation regularLocation : regularLocationList) {
                    regularLocation.setUserId(UserThreadLocal.get().getId());
                    regularLocation.setCustomerEngineId(relationByUserId.getId());
                    regularLocation.setESN(relationByUserId.getEsn());
                    regularLocation.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                    regularLocation.setCreator(UserThreadLocal.get().getId());
                    regularLocation.setFlag(0);
                    regularLocationMapper.insertSelective(regularLocation);
                }
            }
        }
    }

    /**
     * 服务站编号验证芯管家车辆
     */
    @Override
    public ModelAndView xgjVerifyVehicle(Map<String, Object> map) {
        UserT userT = UserThreadLocal.get();
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String paramStr = MapUtils.getString(map, "paramStr", "");
        if(StringUtils.isEmpty(paramStr)){
            ParameterTool.writeResponse(response, 17,"缺少必要参数！");
            return null;
        }
        Map<String,Object> paramMap = JSON.parseObject(paramStr, Map.class);
        String esn = MapUtils.getString(paramMap, "ESN", "");
        String businessNo = MapUtils.getString(paramMap, "BusinessNo", "");
        Integer type = MapUtils.getInteger(paramMap, "Type");
        if(StringUtils.isEmpty(businessNo) || null == type){
            ParameterTool.writeResponse(response, 17,"参数为空！");
            return null;
        }
        try {
            Map<String,Object> data = new HashMap<>();
            //验证 movexID
            String companys = dictionariesTDao.getListByDTableName("xgjBusinessNo");
            List<String> companyList = Arrays.asList(companys.split(","));
            List<SSRepairT> ssRepairTS = serviceStationDaoMapper.queryRepairByBusinessNo(companyList,businessNo);
            if (CollectionUtils.isEmpty(ssRepairTS)) {
                //是否提示 1-是，0否
                data.put("isPrompt",0);
                ParameterTool.writeResponse(response, -99, "请输入正确的服务站代码",data);
                return null;
            }
            ServiceStationT serviceStationT = serviceStationDaoMapper.getStationByStationNo(businessNo);
            if(null != serviceStationT){
                data.put("stationName",serviceStationT.getStationname());
                if(StringUtils.isNotBlank(esn)){
                    String message = "";
                    if(type == 1){
                        List<String> stationNameList = xgjGetUserInfoMapper.getVehicleListByEsn(esn,serviceStationT.getStationno());
                        if(CollectionUtils.isNotEmpty(stationNameList)) {
                            message = "ESN已被其他服务站\"" + StringUtils.join(stationNameList, ",") + "\"绑定，提交后将绑定至当前服务站";
                        }
                    }  else if(type == 2) {
                        List<String> esnList = Arrays.asList(esn.split(","));
                        List<String> esnNoList = xgjGetUserInfoMapper.getVehicleListByEsnList(esnList,serviceStationT.getStationno());
                        if(CollectionUtils.isNotEmpty(esnNoList)) {
                            message = StringUtils.join(esnNoList, ",") + "已被其他服务站绑定，提交后将绑定至当前服务站";
                        }
                    }
                    if(StringUtils.isNotBlank(message)){
                        //是否提示 1-是，0否
                        data.put("isPrompt",1);
                        ParameterTool.writeResponse(response, -77, message,data);
                        return null;
                    }
                }
            }
            ParameterTool.writeResponse(response,0, "",data);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 批量绑车
     * @param map
     * @return
     */
    @Override
    public ModelAndView batchBindVehicles(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String paramStr = MapUtils.getString(map,"paramStr","");
        if(StringUtils.isEmpty(paramStr)){
            ParameterTool.writeResponse(response, 17,"缺少必要参数！");
            return null;
        }
        log.info("批量绑车接口入参paramStr："+paramStr);
        BatchBindVehiclesInfo vehiclesInfo = JSON.parseObject(paramStr, BatchBindVehiclesInfo.class);
        if(null == vehiclesInfo || CollectionUtils.isEmpty(vehiclesInfo.getVehicles())){
            ParameterTool.writeResponse(response, 17, "添加车辆为空！");
            return null;
        }
        List<VehicleInfo> vehicleList = vehiclesInfo.getVehicles();
        for(VehicleInfo vehicle : vehicleList){
            if (StringUtils.isEmpty(vehicle.getEsn()) || StringUtils.isEmpty(vehicle.getPlateNumber()) || null == vehicle.getEquipmentType()) {
                ParameterTool.writeResponse(response, 17, "缺少必要参数！");
                return null;
            }
        }
        List<String> esnList = vehicleList.stream().map(VehicleInfo::getEsn).filter(a -> !StringUtils.isEmpty(a)).collect(Collectors.toList());
        List<String> distEsnList = esnList.stream().map(item -> item).distinct().collect(Collectors.toList());
        if(esnList.size() != distEsnList.size()){
            ParameterTool.writeResponse(response, -99, "ESN重复！");
            return null;
        }

        List<String> esnNoList = esnByCheckList(esnList);
        if(CollectionUtils.isNotEmpty(esnNoList)){
            ParameterTool.writeResponse(response, -99, StringUtils.join(esnNoList, ",") + "发动机序列号错误或不是康明斯发动机，请重新输入！");
            return null;
        }
        UserT userT = UserThreadLocal.get();
        // 加锁处理，避免发生多次提交。
        String lockKey= "batchBindVehicles-" + userT.getUserName() ;
        if (!redisClientUtils.lock(lockKey, 60L)) {
            //防止并发
            ParameterTool.writeErrorResponse(response, -98);
            return null;
        }
        try {
            //验证是否签署了主动服务协议
            ServiceAgreement serviceAggrementDetail = serviceAgrementDao.getServiceAggrementDetail(userT.getId(), 0);
            if (Objects.isNull(serviceAggrementDetail)) {
                ParameterTool.writeResponse(response, -99, "请签署主动服务协议！");
                return null;
            }
            int num = customerEngineRelDao.getRelationByUserIdAndESNList(userT.getId(), esnList);
            if (num > 0) {
                ParameterTool.writeErrorResponse(response, -15,"已添加发动机号，不可重复添加！");
                return null;
            }

            Map<String,Map<String,Object>> fleetEmissionLevelDicListMap = dictionariesTDao.getDicListByDtableName("fleetEmissionLevel");
            Map<String,Map<String,Object>> fleetFuelTypeDicListMap = dictionariesTDao.getDicListByDtableName("fleetFuelType");
            List<String> failedEsnList = new ArrayList<>();
            List<String> esnDataEmptyList = new ArrayList<>();
            List<CustomerEngineRelT> engineRelList = new ArrayList<>();
            for(VehicleInfo vehicle : vehicleList){
                String esn = vehicle.getEsn();
                String plateNumber = vehicle.getPlateNumber();
                //添加数据
                CustomerEngineRelT customerEngineRelT = BeanUtils.convert(vehicle, CustomerEngineRelT.class);
                //esn主数据
                EngineMsg engineMsg = engineMsgDao.getEngineMsgByESNString(esn);
                //调用cip接口获取esn信息
                EsnBasicInfoEntity esnInfo = null;
                EngineMasterData engineMasterData = engineMasterDataMapper.selectByesn(esn);
                if(null != engineMasterData){
                    esnInfo = new EsnBasicInfoEntity();
                    esnInfo.setServiceModelName(engineMasterData.getServiceModelName());
                    esnInfo.setEmissionLevel(engineMasterData.getRelBulletinTelAboEmissionLevel());
                    esnInfo.setFuelType(engineMasterData.getEngineFuelType());
                    esnInfo.setVin(engineMasterData.getBulletinTelVin());
                }
                Map<String, Object> engineMsgMap = new HashMap<>();
                int fleetEmissionLevelDInt = -1;
                int fleetFuelTypeDInt = -1;
                //设置排放信息
                String smn = "";
                if(null != esnInfo){
                    String emissionLevel =  esnInfo.getEmissionLevel();
                    String fuelType = esnInfo.getFuelType();
                    smn =  esnInfo.getServiceModelName();
                    //获取字典表应用类型map(调用cip接口返回的应用类型枚举值)
                    if(MapUtils.isNotEmpty(fleetEmissionLevelDicListMap) && StringUtils.isNotEmpty(emissionLevel) && fleetEmissionLevelDicListMap.containsKey(emissionLevel)){
                        Map<String,Object> fleetEmissionLevelDicMap = MapUtils.getObject(fleetEmissionLevelDicListMap,emissionLevel);
                        if(MapUtils.isNotEmpty(fleetEmissionLevelDicMap)){
                            fleetEmissionLevelDInt = MapUtils.getIntValue(fleetEmissionLevelDicMap,"DInt",-1);
                        }
                    }
                    //获取字典表动力类型ma(调用cip接口返回的应用类型枚举值)
                    if(MapUtils.isNotEmpty(fleetFuelTypeDicListMap) && StringUtils.isNotEmpty(fuelType) && fleetFuelTypeDicListMap.containsKey(fuelType)){
                        Map<String,Object> fleetFuelTypeDicMap = MapUtils.getObject(fleetFuelTypeDicListMap,fuelType);
                        if(MapUtils.isNotEmpty(fleetFuelTypeDicMap)){
                            fleetFuelTypeDInt = MapUtils.getIntValue(fleetFuelTypeDicMap,"DInt",-1);
                        }
                    }
                    engineMsgMap.put("model",emissionLevel);
                } else {
                    esnDataEmptyList.add(esn);
                }
                engineMsgMap.put("EsnApplicationType",fleetEmissionLevelDInt);
                engineMsgMap.put("EsnPowerType",fleetFuelTypeDInt);
                engineMsgMap.put("ESN", esn);
                if(StringUtils.isNotEmpty(smn)){
                    engineMsgMap.put("SMN", smn);
                }
                engineMsgMap.put("equipmentNo", plateNumber);
                if(null == engineMsg){
                    //保存发动机信息
                    engineMsgDao.newInsertEngineMsg(engineMsgMap);
                    //将新插入发动机信息ID放入关联表中
                    customerEngineRelT.setEngineMsgId(MapUtils.getLong(engineMsgMap, "id"));
                }else{
                    engineMsgMap.put("id", engineMsg.getId());
                    if(null == esnInfo){
                        engineMsgMap.put("model", engineMsg.getModel());
                    }
                    engineMsgDao.updateEngineMsg(engineMsgMap);
                    customerEngineRelT.setEngineMsgId(engineMsg.getId());
                }
                customerEngineRelT.setEsn(esn);
                customerEngineRelT.setUserId(userT.getId());
                customerEngineRelT.setPhone(userT.getPhone());
                customerEngineRelT.setPlateNumber(plateNumber);
                customerEngineRelT.setSmnName(smn);
                customerEngineRelT.setNewVIN(vehicle.getVin());
                customerEngineRelT.setCreator(userT.getId());
                customerEngineRelT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                if(StringUtils.isNotBlank(vehiclesInfo.getBusinessNo())){
                    customerEngineRelT.setBusinessNo(vehiclesInfo.getBusinessNo());
                }
                if(StringUtils.isNotBlank(vehiclesInfo.getInviteCode())){
                    customerEngineRelT.setInviteCode(vehiclesInfo.getInviteCode());
                }
                if(null != vehiclesInfo.getHousekeepStatus()){
                    customerEngineRelT.setHousekeepStatus(vehiclesInfo.getHousekeepStatus());
                }
                //百万圆桌绑车
                inviteUserService.addBwyzBind(esn, userT.getId());
                //添加用户引流渠道为 设备归属
                ConductionInfo conductionInfo = userTDao.getConductionByUserId(userT.getId());
                customerEngineRelT.setSalesChannel(null != conductionInfo ? conductionInfo.getChannel() : "");
                int i = customerEngineRelDao.addVehicle(customerEngineRelT);
                //ocrDrivingLicenseTMapper
                //保存ocr的数据
                if (vehicle.getVehicleLicense()!=null) {
                    Map<String,Object> ocrDrivingLicenseMap = new HashMap<>();
                    ocrDrivingLicenseMap.put("CustomerEngineId",customerEngineRelT.getId());
                    ocrDrivingLicenseMap.put("Address",vehicle.getVehicleLicense().getAddress());
                    ocrDrivingLicenseMap.put("EngineNumber",vehicle.getVehicleLicense().getEngineNumber());
                    ocrDrivingLicenseMap.put("IssueDate",vehicle.getVehicleLicense().getIssueDate());
                    ocrDrivingLicenseMap.put("Model",vehicle.getVehicleLicense().getModel());
                    ocrDrivingLicenseMap.put("Owner",vehicle.getVehicleLicense().getOwner());
                    ocrDrivingLicenseMap.put("LicensePlateNumber",vehicle.getVehicleLicense().getLicensePlateNumber());
                    ocrDrivingLicenseMap.put("RegistrationDate",vehicle.getVehicleLicense().getRegistrationDate());
                    ocrDrivingLicenseMap.put("UseNature",vehicle.getVehicleLicense().getUseNature());
                    ocrDrivingLicenseMap.put("VehicleType",vehicle.getVehicleLicense().getVehicleType());
                    ocrDrivingLicenseMap.put("VinCode",vehicle.getVehicleLicense().getVinCode());
                    ocrDrivingLicenseMap.put("IssueAuthority",vehicle.getVehicleLicense().getIssueAuthority());
                    ocrDrivingLicenseMap.put("OpLicensePlateNumber",vehicle.getVehicleLicense().getOpLicensePlateNumber());
                    ocrDrivingLicenseMap.put("InspectionRecord",vehicle.getVehicleLicense().getInspectionRecord());
                    ocrDrivingLicenseMap.put("PassengerCapacity",vehicle.getVehicleLicense().getPassengerCapacity());
                    ocrDrivingLicenseMap.put("TotalWeight",vehicle.getVehicleLicense().getTotalWeight());
                    ocrDrivingLicenseMap.put("PermittedWeight",vehicle.getVehicleLicense().getPermittedWeight());
                    ocrDrivingLicenseMap.put("OverallDimension",vehicle.getVehicleLicense().getOverallDimension());
                    ocrDrivingLicenseMap.put("TractionWeight",vehicle.getVehicleLicense().getTractionWeight());
                    ocrDrivingLicenseMap.put("EnergySign",vehicle.getVehicleLicense().getEnergySign());
                    ocrDrivingLicenseMap.put("RecordNumber",vehicle.getVehicleLicense().getRecordNumber());
                    ocrDrivingLicenseMap.put("Remarks",vehicle.getVehicleLicense().getRemarks());
                    ocrDrivingLicenseMap.put("BarcodeNumber",vehicle.getVehicleLicense().getBarcodeNumber());
                    ocrDrivingLicenseMap.put("Flag",0);
                    ocrDrivingLicenseMap.put("Creator", userT.getId());
                    // 获取实际当前时间(服务器时间加8小时)
                    ocrDrivingLicenseMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
                    ocrVehicleLicenseTMapper.insertSelective(ocrDrivingLicenseMap);
                }
                if(i <= 0){
                    failedEsnList.add(esn);
                } else {
                    engineRelList.add(customerEngineRelT);
                }
            }
            this.bindVehicleOtherOperations(engineRelList,esnDataEmptyList,userT,request);

            //绑车完成新手活动
            cipServiceApi.finishNeophyteTaskUser("bindVehicle","绑定esn：" + vehicleList.get(0).getEsn(),request.getHeader("userid"),request.getHeader("Authorization"));

            if(CollectionUtils.isNotEmpty(failedEsnList)){
                Map<String,Object> esnMap = new HashMap<>();
                esnMap.put("failedEsnList",failedEsnList);
                ParameterTool.writeResponse(response, 0, "部分车辆添加成功",esnMap);
                return null;
            }
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ParameterTool.writeErrorResponse(response);
        } finally {
            //释放锁
            redisClientUtils.delkey(lockKey);
        }
        return null;
    }

    /**
     * 批量绑车并签协议
     * @param map
     * @return
     */
    @Override
    public ModelAndView batchBindVehiclesSign(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String paramStr = MapUtils.getString(map,"paramStr","");
        if(StringUtils.isEmpty(paramStr)){
            ParameterTool.writeResponse(response, 17,"缺少必要参数！");
            return null;
        }
        log.info("批量绑车签协议接口入参paramStr："+paramStr);
        BatchBindVehiclesInfo vehiclesInfo = JSON.parseObject(paramStr, BatchBindVehiclesInfo.class);
        if(null == vehiclesInfo || CollectionUtils.isEmpty(vehiclesInfo.getVehicles())){
            ParameterTool.writeResponse(response, 17, "添加车辆为空！");
            return null;
        }
        if(StringUtils.isBlank(vehiclesInfo.getUserId())){
            ParameterTool.writeResponse(response, 17, "用户id为空！");
            return null;
        }
        List<VehicleInfo> vehicleList = vehiclesInfo.getVehicles();
        for(VehicleInfo vehicle : vehicleList){
            if (StringUtils.isEmpty(vehicle.getEsn()) || StringUtils.isEmpty(vehicle.getPlateNumber()) || null == vehicle.getEquipmentType()) {
                ParameterTool.writeResponse(response, 17, "缺少必要参数！");
                return null;
            }
        }
        List<String> esnList = vehicleList.stream().map(VehicleInfo::getEsn).filter(a -> !StringUtils.isEmpty(a)).collect(Collectors.toList());
        List<String> distEsnList = esnList.stream().map(item -> item).distinct().collect(Collectors.toList());
        if(esnList.size() != distEsnList.size()){
            ParameterTool.writeResponse(response, -99, "ESN重复！");
            return null;
        }

        List<String> esnNoList = esnByCheckList(esnList);
        if(CollectionUtils.isNotEmpty(esnNoList)){
            ParameterTool.writeResponse(response, -99, StringUtils.join(esnNoList, ",") + "发动机序列号错误或不是康明斯发动机，请重新输入！");
            return null;
        }
        UserT userT = null;
        if(null != vehiclesInfo.getChannel() && vehiclesInfo.getChannel() != 1){
            Long userid = userChannelTMapper.getUserChannelByExternalUserIdAndChannel(vehiclesInfo.getUserId(), String.valueOf(vehiclesInfo.getChannel()));
            if(null != userid){
                userT = userTDao.selectById(userid);
            }
        } else {
            userT = userTDao.selectById(Long.valueOf(vehiclesInfo.getUserId()));
        }
        if(null == userT){
            ParameterTool.writeResponse(response, 17, "用户为空！");
            return null;
        }

        // 加锁处理，避免发生多次提交。
        String lockKey= "batchBindVehiclesSign-" + userT.getUserName() ;
        if (!redisClientUtils.lock(lockKey, 60L)) {
            //防止并发
            ParameterTool.writeErrorResponse(response, -98);
            return null;
        }
        try {
            //验证是否签署了主动服务协议
            ServiceAgreement serviceAggrementDetail = serviceAgrementDao.getServiceAggrementDetail(userT.getId(), 0);
            if (Objects.isNull(serviceAggrementDetail)) {
                ServiceAgreement serviceAgreement = new ServiceAgreement();
                serviceAgreement.setUserId(userT.getId());
                serviceAgreement.setSignTime(Date_Util.getOnlyDate());
                serviceAgreement.setTerminateTime(Date_Util.addMonth(60));
                serviceAgreement.setCreator(userT.getId());
                serviceAgreement.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                serviceAgreement.setType(0);
                String coreManagerAgreement = dictionariesTDao.getListByDTableName("CoreManagerAgreement");
                serviceAgreement.setVersion(Integer.valueOf(coreManagerAgreement));
                serviceAgrementDao.signServiceAgreement(serviceAgreement);
            }
            Map<String,Map<String,Object>> fleetEmissionLevelDicListMap = dictionariesTDao.getDicListByDtableName("fleetEmissionLevel");
            Map<String,Map<String,Object>> fleetFuelTypeDicListMap = dictionariesTDao.getDicListByDtableName("fleetFuelType");
            List<String> esnDataEmptyList = new ArrayList<>();
            List<CustomerEngineRelT> engineRelList = new ArrayList<>();
            for(VehicleInfo vehicle : vehicleList){
                String esn = vehicle.getEsn();
                List<String> esnsList = new ArrayList<>();
                esnsList.add(esn);
                int num = customerEngineRelDao.getRelationByUserIdAndESNList(userT.getId(), esnsList);
                if(num <= 0){
                    String plateNumber = vehicle.getPlateNumber();
                    //添加数据
                    CustomerEngineRelT customerEngineRelT = BeanUtils.convert(vehicle, CustomerEngineRelT.class);
                    //esn主数据
                    EngineMsg engineMsg = engineMsgDao.getEngineMsgByESNString(esn);
                    //调用cip接口获取esn信息
                    EsnBasicInfoEntity esnInfo = null;
                    EngineMasterData engineMasterData = engineMasterDataMapper.selectByesn(esn);
                    if(null != engineMasterData){
                        esnInfo = new EsnBasicInfoEntity();
                        esnInfo.setServiceModelName(engineMasterData.getServiceModelName());
                        esnInfo.setEmissionLevel(engineMasterData.getRelBulletinTelAboEmissionLevel());
                        esnInfo.setFuelType(engineMasterData.getEngineFuelType());
                        esnInfo.setVin(engineMasterData.getBulletinTelVin());
                    }
                    Map<String, Object> engineMsgMap = new HashMap<>();
                    int fleetEmissionLevelDInt = -1;
                    int fleetFuelTypeDInt = -1;
                    //设置排放信息
                    String smn = "";
                    if(null != esnInfo){
                        String emissionLevel =  esnInfo.getEmissionLevel();
                        String fuelType = esnInfo.getFuelType();
                        smn =  esnInfo.getServiceModelName();
                        //获取字典表应用类型map(调用cip接口返回的应用类型枚举值)
                        if(MapUtils.isNotEmpty(fleetEmissionLevelDicListMap) && StringUtils.isNotEmpty(emissionLevel) && fleetEmissionLevelDicListMap.containsKey(emissionLevel)){
                            Map<String,Object> fleetEmissionLevelDicMap = MapUtils.getObject(fleetEmissionLevelDicListMap,emissionLevel);
                            if(MapUtils.isNotEmpty(fleetEmissionLevelDicMap)){
                                fleetEmissionLevelDInt = MapUtils.getIntValue(fleetEmissionLevelDicMap,"DInt",-1);
                            }
                        }
                        //获取字典表动力类型ma(调用cip接口返回的应用类型枚举值)
                        if(MapUtils.isNotEmpty(fleetFuelTypeDicListMap) && StringUtils.isNotEmpty(fuelType) && fleetFuelTypeDicListMap.containsKey(fuelType)){
                            Map<String,Object> fleetFuelTypeDicMap = MapUtils.getObject(fleetFuelTypeDicListMap,fuelType);
                            if(MapUtils.isNotEmpty(fleetFuelTypeDicMap)){
                                fleetFuelTypeDInt = MapUtils.getIntValue(fleetFuelTypeDicMap,"DInt",-1);
                            }
                        }
                        engineMsgMap.put("model",emissionLevel);
                    } else {
                        esnDataEmptyList.add(esn);
                    }
                    engineMsgMap.put("EsnApplicationType",fleetEmissionLevelDInt);
                    engineMsgMap.put("EsnPowerType",fleetFuelTypeDInt);
                    engineMsgMap.put("ESN", esn);
                    if(StringUtils.isNotEmpty(smn)){
                        engineMsgMap.put("SMN", smn);
                    }
                    engineMsgMap.put("equipmentNo", plateNumber);
                    if(null == engineMsg){
                        //保存发动机信息
                        engineMsgDao.newInsertEngineMsg(engineMsgMap);
                        //将新插入发动机信息ID放入关联表中
                        customerEngineRelT.setEngineMsgId(MapUtils.getLong(engineMsgMap, "id"));
                    }else{
                        engineMsgMap.put("id", engineMsg.getId());
                        if(null == esnInfo){
                            engineMsgMap.put("model", engineMsg.getModel());
                        }
                        engineMsgDao.updateEngineMsg(engineMsgMap);
                        customerEngineRelT.setEngineMsgId(engineMsg.getId());
                    }
                    customerEngineRelT.setEsn(esn);
                    customerEngineRelT.setUserId(userT.getId());
                    customerEngineRelT.setPhone(userT.getPhone());
                    customerEngineRelT.setPlateNumber(plateNumber);
                    customerEngineRelT.setSmnName(smn);
                    customerEngineRelT.setNewVIN(vehicle.getVin());
                    customerEngineRelT.setCreator(userT.getId());
                    customerEngineRelT.setCreateTime(LocalTimeUtil.getRealCurrentTime());
                    if(StringUtils.isNotBlank(vehiclesInfo.getBusinessNo())){
                        customerEngineRelT.setBusinessNo(vehiclesInfo.getBusinessNo());
                    }
                    if(StringUtils.isNotBlank(vehiclesInfo.getInviteCode())){
                        customerEngineRelT.setInviteCode(vehiclesInfo.getInviteCode());
                    }
                    if(null != vehiclesInfo.getHousekeepStatus()){
                        customerEngineRelT.setHousekeepStatus(vehiclesInfo.getHousekeepStatus());
                    }
                    //百万圆桌绑车
                    inviteUserService.addBwyzBind(esn, userT.getId());

                    int i = customerEngineRelDao.addVehicle(customerEngineRelT);
                    //ocrDrivingLicenseTMapper
                    //保存ocr的数据
                    if (vehicle.getVehicleLicense()!=null) {
                        Map<String,Object> ocrDrivingLicenseMap = new HashMap<>();
                        ocrDrivingLicenseMap.put("CustomerEngineId",customerEngineRelT.getId());
                        ocrDrivingLicenseMap.put("Address",vehicle.getVehicleLicense().getAddress());
                        ocrDrivingLicenseMap.put("EngineNumber",vehicle.getVehicleLicense().getEngineNumber());
                        ocrDrivingLicenseMap.put("IssueDate",vehicle.getVehicleLicense().getIssueDate());
                        ocrDrivingLicenseMap.put("Model",vehicle.getVehicleLicense().getModel());
                        ocrDrivingLicenseMap.put("Owner",vehicle.getVehicleLicense().getOwner());
                        ocrDrivingLicenseMap.put("LicensePlateNumber",vehicle.getVehicleLicense().getLicensePlateNumber());
                        ocrDrivingLicenseMap.put("RegistrationDate",vehicle.getVehicleLicense().getRegistrationDate());
                        ocrDrivingLicenseMap.put("UseNature",vehicle.getVehicleLicense().getUseNature());
                        ocrDrivingLicenseMap.put("VehicleType",vehicle.getVehicleLicense().getVehicleType());
                        ocrDrivingLicenseMap.put("VinCode",vehicle.getVehicleLicense().getVinCode());
                        ocrDrivingLicenseMap.put("IssueAuthority",vehicle.getVehicleLicense().getIssueAuthority());
                        ocrDrivingLicenseMap.put("OpLicensePlateNumber",vehicle.getVehicleLicense().getOpLicensePlateNumber());
                        ocrDrivingLicenseMap.put("InspectionRecord",vehicle.getVehicleLicense().getInspectionRecord());
                        ocrDrivingLicenseMap.put("PassengerCapacity",vehicle.getVehicleLicense().getPassengerCapacity());
                        ocrDrivingLicenseMap.put("TotalWeight",vehicle.getVehicleLicense().getTotalWeight());
                        ocrDrivingLicenseMap.put("PermittedWeight",vehicle.getVehicleLicense().getPermittedWeight());
                        ocrDrivingLicenseMap.put("OverallDimension",vehicle.getVehicleLicense().getOverallDimension());
                        ocrDrivingLicenseMap.put("TractionWeight",vehicle.getVehicleLicense().getTractionWeight());
                        ocrDrivingLicenseMap.put("EnergySign",vehicle.getVehicleLicense().getEnergySign());
                        ocrDrivingLicenseMap.put("RecordNumber",vehicle.getVehicleLicense().getRecordNumber());
                        ocrDrivingLicenseMap.put("Remarks",vehicle.getVehicleLicense().getRemarks());
                        ocrDrivingLicenseMap.put("BarcodeNumber",vehicle.getVehicleLicense().getBarcodeNumber());
                        ocrDrivingLicenseMap.put("Flag",0);
                        ocrDrivingLicenseMap.put("Creator", userT.getId());
                        // 获取实际当前时间(服务器时间加8小时)
                        ocrDrivingLicenseMap.put("CreateTime", LocalTimeUtil.getRealCurrentTime());
                        ocrVehicleLicenseTMapper.insertSelective(ocrDrivingLicenseMap);
                    }
                    if(i > 0){
                        engineRelList.add(customerEngineRelT);
                    }
                }
            }
            this.bindVehicleOtherOperations(engineRelList,esnDataEmptyList,userT,request);
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ParameterTool.writeErrorResponse(response);
        } finally {
            //释放锁
            redisClientUtils.delkey(lockKey);
        }
        return null;
    }

    /**
     * 绑车其他操作
     * @param engineRelList
     * @return
     */
    @Async
    public void bindVehicleOtherOperations(List<CustomerEngineRelT> engineRelList,List<String> esnDataEmptyList,UserT userT,HttpServletRequest request) {
        if(CollectionUtils.isNotEmpty(engineRelList)) {
            log.info("绑车其他操作:"+engineRelList);
            for(CustomerEngineRelT customerEngineRelT : engineRelList){
                String esn = customerEngineRelT.getEsn();
                String plateNumber = customerEngineRelT.getPlateNumber();
                String businessNo = customerEngineRelT.getBusinessNo();
                int equipmentType = customerEngineRelT.getEquipmentType();
                //首次绑车添加蜜值
                int customerEngineRelTCount = customerEngineRelDao.getCountByUserId(userT.getId());
                if (customerEngineRelTCount <= 0) {
                    //同步添加蜜值的方法
                    syncAddhoney(request);
                }
                Long count = saDao.isSignAgreement(userT.getId(), LocalTimeUtil.getRealCurrentTime());
                if (count > 0) {//用户如果签署了主动服务协议，将发动机信息同步至salesforce
                    asyncCrmService.syncServiceAgreementAndEngineToCRM(userT, esn, true, true);
                    //同步esn给cip
                    List<String> esnList = new ArrayList<>();
                    esnList.add(esn);
                    CipApiUtils.getCipServiceApi().synchronizationEsn(ActionEnum.ADD.getValue(), esnList,businessNo);
                }
                //月度报告实时更新ESN  同步给春卷团队
                syncEsnAndUserId.asSyncEsnAndUserIdAddOne(esn, plateNumber, userT.getId(),customerEngineRelT.getDrivingLicensePhotoUrl(), "1", customerEngineRelT.getInviteCode(),customerEngineRelT.getSalesChannel());
                //同步老友汇车辆
                externalDataSynchroService.pushLyhEsn(userT.getId(), esn, plateNumber, "ADD");
                //绑车数据至芯管家后台
                if (StringUtils.isNotBlank(businessNo)) {
                    ServiceStationT serviceStationT = serviceStationDaoMapper.getStationByStationNo(businessNo);
                    if (null != serviceStationT) {
                        List<String> stationNameList = xgjGetUserInfoMapper.getVehicleListByEsn(esn, serviceStationT.getStationno());
                        String headerType = request.getHeader("type");
                        int dataSource = StringUtils.isNotBlank(headerType) && headerType.equals("1") ? 3 : 2;
                        FleetAndEsnRelationRequest xgjRequest = new FleetAndEsnRelationRequest();
                        xgjRequest.setEsn(esn);
                        xgjRequest.setPlatenum(plateNumber);
                        xgjRequest.setBusinessNo(businessNo);
                        xgjRequest.setDataSource(dataSource);
                        if (CollectionUtils.isNotEmpty(stationNameList)) {
                            xgjRequest.setOperate("U");
                        } else {
                            xgjRequest.setOperate("I");
                        }
                        xgjRequest.setVehicleType(equipmentType == 1 ? 1 : 2);
                        String ocrVIN = customerEngineRelT.getNewVIN();
                        EngineMasterData engineMasterData = engineMasterDataMapper.selectByesn(esn);
                        String cipvin = StringUtils.isBlank(ocrVIN) ? null != engineMasterData ? engineMasterData.getBulletinTelVin() : "" : ocrVIN;
                        xgjRequest.setVin(cipvin);
                        CipApiUtils.getCipServiceApi().syncBindVehicle(xgjRequest, userT.getId());
                    }
                }
            }
        }
        //esn主数据没有查询到
        if(CollectionUtils.isNotEmpty(esnDataEmptyList)) {
           for(String esn : esnDataEmptyList){
               //调用cip接口获取esn信息
               EsnBasicInfoEntity esnInfo = null;
               CipResponeEntity respone = CipApiUtils.getCipServiceApi().getEsnInfo(esn);
               if (null != respone) {
                   if (respone.getCode().equals(0)) {
                       esnInfo = (EsnBasicInfoEntity) JSONObject.toBean(respone.getData(), EsnBasicInfoEntity.class);
                   }
               }
               if(null != esnInfo){
                   Map<String, Object> engineMsgMap = new HashMap<>();
                   int fleetEmissionLevelDInt = -1;
                   int fleetFuelTypeDInt = -1;
                   String emissionLevel =  esnInfo.getEmissionLevel();
                   String fuelType = esnInfo.getFuelType();
                   String smn = esnInfo.getServiceModelName();
                   //获取字典表应用类型map(调用cip接口返回的应用类型枚举值)
                   Map<String,Map<String,Object>> fleetEmissionLevelDicListMap = dictionariesTDao.getDicListByDtableName("fleetEmissionLevel");
                   if(MapUtils.isNotEmpty(fleetEmissionLevelDicListMap) && StringUtils.isNotEmpty(emissionLevel) && fleetEmissionLevelDicListMap.containsKey(emissionLevel)){
                       Map<String,Object> fleetEmissionLevelDicMap = MapUtils.getObject(fleetEmissionLevelDicListMap,emissionLevel);
                       if(MapUtils.isNotEmpty(fleetEmissionLevelDicMap)){
                           fleetEmissionLevelDInt = MapUtils.getIntValue(fleetEmissionLevelDicMap,"DInt",-1);
                       }
                   }
                   //获取字典表动力类型ma(调用cip接口返回的应用类型枚举值)
                   Map<String,Map<String,Object>> fleetFuelTypeDicListMap = dictionariesTDao.getDicListByDtableName("fleetFuelType");
                   if(MapUtils.isNotEmpty(fleetFuelTypeDicListMap) && StringUtils.isNotEmpty(fuelType) && fleetFuelTypeDicListMap.containsKey(fuelType)){
                       Map<String,Object> fleetFuelTypeDicMap = MapUtils.getObject(fleetFuelTypeDicListMap,fuelType);
                       if(MapUtils.isNotEmpty(fleetFuelTypeDicMap)){
                           fleetFuelTypeDInt = MapUtils.getIntValue(fleetFuelTypeDicMap,"DInt",-1);
                       }
                   }
                   engineMsgMap.put("SMN",smn);
                   engineMsgMap.put("model",emissionLevel);
                   engineMsgMap.put("esnApplicationType",fleetEmissionLevelDInt);
                   engineMsgMap.put("esnPowerType",fleetFuelTypeDInt);
                   engineMsgMap.put("ESN",esn);
                   engineMsgDao.updateMsgByEsn(engineMsgMap);
               }


           }
        }

    }


    /**
     * 根据esn校验是否符合
     */
    @Override
    public boolean esnByCheck(String esnStr) {
        boolean success = false;
        if(StringUtils.isNotBlank(esnStr) && StringUtils.isNumeric(esnStr)){
            Long esn = Long.valueOf(esnStr);
            List<BindESNWhiteT> list = customerEngineRelDao.getBindESNWhiteList();
            if(CollectionUtils.isNotEmpty(list)){
                for(BindESNWhiteT bind : list){
                    if(null != bind.getEsnMin() && null != bind.getEsnMax()){
                        if(bind.getEsnMin() <= esn && bind.getEsnMax() >= esn){
                            success = true;
                        }
                    }
                }
            }
        }
        return success;
    }

    /**
     * 根据esnlist校验是否符合
     */
    public List<String> esnByCheckList(List<String> esnList) {
        List<String> esnNoList = new ArrayList<>();
        List<BindESNWhiteT> list = customerEngineRelDao.getBindESNWhiteList();
        if(CollectionUtils.isNotEmpty(esnList) && CollectionUtils.isNotEmpty(list)){
            for(String esnStr : esnList){
                boolean success = false;
                if(StringUtils.isNotBlank(esnStr) && StringUtils.isNumeric(esnStr)){
                    Long esn = Long.valueOf(esnStr);
                    for(BindESNWhiteT bind : list){
                        if(null != bind.getEsnMin() && null != bind.getEsnMax()){
                            if(bind.getEsnMin() <= esn && bind.getEsnMax() >= esn){
                                success = true;
                            }
                        }
                    }
                }
                if(!success){
                    esnNoList.add(esnStr);
                }
            }
        }

        return esnNoList;
    }

    /**
     * 根据esn获取最新设备详细
     * @param esn
     * @return
     */
    @Override
    public CustomerEngineRelResponse getEngineByEsn(String esn) {
        return customerEngineRelDao.getEngineByEsn(esn);
    }


    /**
     * 获取用户商用车列表
     */
    @Override
    public ModelAndView getCommercialCarList(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        List<GetCommercialCarListResponse> commercialCarList = customerEngineRelDao.getCommercialCarList(userT.getId());
        Integer integer = MapUtils.getInteger(map, "needFlag", 1);
        if(integer==1){
            for(GetCommercialCarListResponse listResponse : commercialCarList){
                if(StringUtils.isNotBlank(listResponse.getEsn())){
                    CipHealthCheckResponse healthCheck = cipServiceApi.getCipHealthCheck(listResponse.getEsn());
                    if(null != healthCheck){
                        listResponse.setHealthState(healthCheck.getHealthState());
                        listResponse.setHealthScore(healthCheck.getHealthScore());
                    }
                }
            }
        }

        Map<String,Object> data = new HashMap<>();
        data.put("customerEngineRelList",commercialCarList);
        ParameterTool.writeSuccessResponse(response, data);
        return null;
    }


    /**
     * 提交完善车辆信息接口（油耗导航）
     */
    @Override
    @Transactional
    public ModelAndView submitImproveCarMsg(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String paramStr = MapUtils.getString(map,"paramStr","");
        if(StringUtils.isEmpty(paramStr)){
            ParameterTool.writeResponse(response, 17,"缺少必要参数！");
            return null;
        }
        Map<String,Object> paramMap = JSON.parseObject(paramStr, Map.class);
        UserT userT = UserThreadLocal.get();
        String currentTime = LocalTimeUtil.getRealCurrentTime();
        long customerEngineRelId = MapUtils.getLongValue(paramMap,"CustomerEngineRelId",-1);
        int finalVehicleType = MapUtils.getIntValue(paramMap,"FinalVehicleType",-1);
        int finalApplicationClass = MapUtils.getIntValue(paramMap,"FinalApplicationClass",-1);
        if (customerEngineRelId == -1 || finalVehicleType == -1 || finalApplicationClass == -1) {
            ParameterTool.writeResponse(response, 17, "缺少必要参数！");
            return null;
        }
        paramMap.put("Updator", userT.getId());
        paramMap.put("UpdateTime", currentTime);
        paramMap.put("IsImproveCarMsg", 1);
        paramMap.put("CustomerEngineRelID", customerEngineRelId);
        customerEngineRelDao.newUpdateCustomerEngineRel(paramMap);
        // 是否包含起点终点
        String startLongitude = MapUtils.getString(paramMap, "StartLongitude");
        String startLatitude = MapUtils.getString(paramMap, "StartLatitude");
        String endLongitude = MapUtils.getString(paramMap, "EndLongitude");
        String endLatitude = MapUtils.getString(paramMap, "EndLatitude");
        if (StringUtils.isNotBlank(startLongitude) &&
                StringUtils.isNotBlank(startLatitude) &&
                StringUtils.isNotBlank(endLongitude) &&
                StringUtils.isNotBlank(endLatitude)) {
            int isRecommend = loadMsgRelationService.getIsRecommend(customerEngineRelId);
            if (isRecommend > 0) {
                CustomerEngineRelLoadMsgRelationT isRecommendClass = loadMsgRelationService.getIsRecommendClass(customerEngineRelId);
                isRecommendClass.setFlag(-1);
                isRecommendClass.setDeleter(userT.getId());
                isRecommendClass.setDeleteTime(LocalTimeUtil.getRealCurrentTime());
                loadMsgRelationService.update(isRecommendClass);
            }
            String startingPoint = MapUtils.getString(paramMap, "StartingPoint");
            String endPoint = MapUtils.getString(paramMap, "EndPoint");
            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("CustomerEngineRelId", customerEngineRelId);
//                objectMap.put("CarRealTotalMassType",);
//                objectMap.put("CarRealTotalMass",);
//                objectMap.put("CarRealHeight",);
            objectMap.put("StartingPoint", startingPoint);
            objectMap.put("EndPoint", endPoint);
            objectMap.put("StartLongitude", startLongitude);
            objectMap.put("StartLatitude", startLatitude);
            objectMap.put("EndLongitude", endLongitude);
            objectMap.put("EndLatitude", endLatitude);
            objectMap.put("EndLatitude", endLatitude);
            objectMap.put("IsRecommend", 1);
            loadMsgRelationService.save(objectMap);
        }
        CustomerEngineRelT relationByUserId = customerEngineRelDao.getCustomerEngineRelById(customerEngineRelId);
        regularLocationMapper.updateByUserIdAndEsn(userT.getId(),customerEngineRelId);
        //添加常规点
        this.saveRegularLocation(paramMap,relationByUserId);
        ParameterTool.writeSuccessResponse(response);
        return null;
    }


    /**
     * 根据esn获取所有绑定该esn的用户信息（除了本人）
     */
    @Override
    public ModelAndView getCustomerEngineRelByEsn(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        Long customerEngineRelId = MapUtils.getLongValue(map,"customerEngineRelId",-1);
        if(null == userT || customerEngineRelId == -1){
            ParameterTool.writeErrorResponse(response, -5);
            return null;
        }
        //获取正常的未被车主取消的用户车辆信息
        List<Map<String,Object>> customerIsCancelledAuthList = customerEngineRelDao.getCustomerIsCancelledAuthByEsn(customerEngineRelId,userT.getId());
        //获取被车主解除授权的用户车辆信息
        List<Map<String,Object>> customerNotIsCancelledAuthList = customerEngineRelDao.getCustomerNotIsCancelledAuthByEsn(customerEngineRelId,userT.getId());
        //将被车主主动解除授权的用户信息放到集合的最后
        List<Map<String,Object>> customerEngineRelList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(customerIsCancelledAuthList)){
            customerEngineRelList.addAll(customerIsCancelledAuthList);
        }
        if(CollectionUtils.isNotEmpty(customerNotIsCancelledAuthList)){
            customerEngineRelList.addAll(customerNotIsCancelledAuthList);
        }
        //处理用户车辆信息数据，手机号中间四位数加密
        if(CollectionUtils.isNotEmpty(customerEngineRelList)){
            customerEngineRelList.stream().forEach(customerEngineRelMap->{
                String phone = MapUtils.getString(customerEngineRelMap,"phone","");
                String userName = MapUtils.getString(customerEngineRelMap,"userName","");
                if(StringUtils.isNotEmpty(phone) && phone.length() == 11){
                    phone = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
                }
                if(StringUtils.isNotEmpty(userName) && phone.length() == 11){
                    userName = userName.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
                }
                customerEngineRelMap.put("phone",phone);
                customerEngineRelMap.put("userName",userName);
            });
        }
        Map<String, Object> data = new HashMap<>();
        data.put("customerEngineRelList", customerEngineRelList);
        ParameterTool.writeSuccessResponse(response, data);
        return null;
    }



    /**
     * 车主解除授权接口
     */
    @Override
    public ModelAndView carOwnerUnBindAuth(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        String realCurrentTime = LocalTimeUtil.getRealCurrentTime();
        //1.验证参数
        Long customerEngineRelId = MapUtils.getLongValue(map,"customerEngineRelId",-1);
        if(null == userT || customerEngineRelId == -1){
            ParameterTool.writeErrorResponse(response, -5);
            return null;
        }
        //2.修改用户绑定设备表数据
        CustomerEngineRelT customerEngineRelT = customerEngineRelDao.getCustomerEngineRelById(customerEngineRelId);
        Map<String, Object> updteCustomerEngineRelMap = new HashMap<>();
        updteCustomerEngineRelMap.put("Flag",-1);
        updteCustomerEngineRelMap.put("IsCancelledAuth",1);
        updteCustomerEngineRelMap.put("Updator",userT.getId());
        updteCustomerEngineRelMap.put("UpdateTime",realCurrentTime);
        updteCustomerEngineRelMap.put("Deleter",userT.getId());
        updteCustomerEngineRelMap.put("DeleteTime",realCurrentTime);
        updteCustomerEngineRelMap.put("CustomerEngineRelID",customerEngineRelId);
        customerEngineRelDao.newUpdateCustomerEngineRel(updteCustomerEngineRelMap);
        if(null != customerEngineRelT){
            //3.调用公共方法
            //获取被解除授权的用户的信息
            UserT unBindAuthUser = userTDao.selectById(customerEngineRelT.getUserId());
            userDeleteOrUnBindAuthPublicMethod(customerEngineRelT, unBindAuthUser, realCurrentTime, map);
            if(customerEngineRelT.getCertifiedOwnerApplyId() != 0){
                //4.如果用户存在认证车主的申请   修改认证车主申请为审核不通过
                CertifiedOwnerApplyT certifiedOwnerApplyT = new CertifiedOwnerApplyT();
                certifiedOwnerApplyT.setCertifiedStatus(2);
                certifiedOwnerApplyT.setAuditNoPassReason("您已被车主解除授权。");
                certifiedOwnerApplyT.setUpdator(userT.getId());
                certifiedOwnerApplyT.setUpdateTime(realCurrentTime);
                certifiedOwnerApplyT.setId(customerEngineRelT.getCertifiedOwnerApplyId());
                int num = certifiedOwnerApplyDao.updateSelective(certifiedOwnerApplyT);
                if(num > 0){
                    //5.插入操作记录表
                    CertifiedOwnerApplyRecordT certifiedOwnerApplyRecordT = new CertifiedOwnerApplyRecordT();
                    certifiedOwnerApplyRecordT.setCertifiedStatus(2);
                    certifiedOwnerApplyRecordT.setCertifiedOwnerApplyId(customerEngineRelT.getCertifiedOwnerApplyId());
                    certifiedOwnerApplyRecordT.setAuditNoPassReason("您已被车主解除授权。");
                    certifiedOwnerApplyRecordT.setAuditor(userT.getId());
                    certifiedOwnerApplyRecordT.setAuditTime(realCurrentTime);
                    certifiedOwnerApplyRecordT.setCreateTime(realCurrentTime);
                    certifiedOwnerApplyRecordT.setCreator(userT.getId());
                    certifiedOwnerApplyRecordDao.insertSelective(certifiedOwnerApplyRecordT);
                }

                //6.发送app推送
                List<CertifiedMessagePushRequest> requestList = new ArrayList<>();
                CertifiedMessagePushRequest certifiedMessagePushRequest = new CertifiedMessagePushRequest();
                certifiedMessagePushRequest.setMessage("您的设备号/车牌号："+customerEngineRelT.getVin() +"已认证失败，失败原因：您已被车主解除授权。");
                certifiedMessagePushRequest.setSendType(2);
                certifiedMessagePushRequest.setTitle("车辆认证失败提醒");
                certifiedMessagePushRequest.setUserId(customerEngineRelT.getUserId());
                certifiedMessagePushRequest.setType(180);
                certifiedMessagePushRequest.setTypeDescription("车主认证");
                requestList.add(certifiedMessagePushRequest);
                syncCertifiedMessagePushInfo(requestList,map);
            }
        }
        ParameterTool.writeSuccessResponse(response);
        return null;
    }


    //消息推送
    @Async
    void syncCertifiedMessagePushInfo(List<CertifiedMessagePushRequest> certifiedMessagePushRequests,Map<String,Object> map){
        log.info("进入syncCertifiedMessagePushInfo异步线程");
        String mcMessagePushUrl = messagePushUrl + "/api/notify/sendMessage";
        HttpServletRequest request = (HttpServletRequest)map.get("request");
        Header userId = new BasicHeader("userid",request.getHeader("userid"));
        Header token = new BasicHeader("Authorization",request.getHeader("Authorization"));
        log.info( "远程调用mc接口，车主解除授权推送app消息接口，请求地址为："+mcMessagePushUrl+"，请求参数为："+ JSON.toJSONString(certifiedMessagePushRequests));
        try {
            String response = HttpUtils.postJson(mcMessagePushUrl, JSON.toJSONString(certifiedMessagePushRequests), new ResponseHandler<String>() {
                @Override
                public String handleResponse(HttpResponse response) throws IOException {
                    if (response.getStatusLine().getStatusCode() == 200) {
                        HttpEntity httpEntity = response.getEntity();
                        return EntityUtils.toString(httpEntity);
                    } else {
                        log.error("远程调用mc接口，车主审核消息接口报错，返回结果：" + response);
                    }
                    return null;
                }
            }, userId,token);
            log.info( "远程调用mc接口，车主审核消息接口结束，响应信息为："+response);
        } catch (Exception e) {
            log.error("远程调用mc接口，车主审核消息接口异常，异常原因："+e);
        }
        log.info("执行syncCertifiedMessagePushInfo异步线程结束");
    }

    /**
     * sprint 57  删除或者取消授权设备时，将油耗计算器正在进行中的测量关闭
     */
    public void syncFuelMeasure(String esn, Long userId, HttpServletRequest request) {
        ThreadPoolUtil.newTask(new Thread(() -> {
            String hostrul = PropertiesUtil.getProperties("projectconfig.properties",
                    "mizhi.fuel.abnormalClose");
            Map<String, String> parameter = new HashMap<>();
            parameter.put("esn", esn);
            parameter.put("userId", userId.toString());
            String useridToken = request.getHeader("userid");
            String authorizationToken = request.getHeader("Authorization");
            String token = request.getHeader("Authorization");
            BasicHeader useridHeader = new BasicHeader("userid", useridToken);
            BasicHeader authorizationHeader = new BasicHeader("Authorization", authorizationToken);
            String result = HttpUtils.get(hostrul, parameter, new ResponseHandler<String>() {
                @Override
                public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                    if (response.getStatusLine().getStatusCode() == 200) {
                        HttpEntity httpEntity = response.getEntity();
                        return EntityUtils.toString(httpEntity);
                    }
                    return null;
                }
            }, useridHeader, authorizationHeader);
            if (StringUtils.isNotBlank(result)) {
                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
                Integer status = jsonObject.getInteger("status");
                if (null != status && status == 0) {
                    log.error("调用:" + hostrul + "返回值成功");
                } else {
                    log.error("调用:" + hostrul + "返回值失败,返回值为" + jsonObject.toString() + "参数为:esn" + esn + ",userid:" + userId);
                }
            } else {
                log.error("调用:" + hostrul + "返回值失败,参数为:esn" + esn + ",userid:" + userId);
            }
        }));

    }

    public void syncAddhoney(HttpServletRequest request) {
        ThreadPoolUtil.newTask(new Thread(() -> {
            String hostrul = PropertiesUtil.getProperties("projectconfig.properties",
                    "mizhi.addHoneyByTyingCar");

            String useridToken = request.getHeader("userid");
            String authorizationToken = request.getHeader("Authorization");
            String type = request.getHeader("type");
            BasicHeader useridHeader = new BasicHeader("userid", useridToken);
            BasicHeader authorizationHeader = new BasicHeader("Authorization", authorizationToken);
            BasicHeader typeHeader = new BasicHeader("type", type);
            String result = HttpUtils.postJson(hostrul, new ResponseHandler<String>() {
                @Override
                public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                    if (response.getStatusLine().getStatusCode() == 200) {
                        HttpEntity httpEntity = response.getEntity();
                        return EntityUtils.toString(httpEntity);
                    }
                    return null;
                }
            }, useridHeader, authorizationHeader,typeHeader);
            if (StringUtils.isNotBlank(result)) {
                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(result);
                Integer status = jsonObject.getInteger("status");
                if (null != status && status == 0) {
                    log.error("调用:" + hostrul + "返回值成功");
                } else {
                    log.error("调用:" + hostrul + "返回值失败,返回值为" + jsonObject.toString());
                }
            } else {
                log.error("调用:" + hostrul + "返回值失败,参数为:esn");
            }
        }));

    }

    /**
     * 用户添加设备信息和amt的接口
     *
     * @param map
     * @return
     */
    @Override
    @Transactional
    public ModelAndView addCustomerEngineAndAmt(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        try {
            UserT userT = UserThreadLocal.get();
            map.put("userId", userT.getId());
            map.put("phone", userT.getPhone());
            // 获取实际当前时间(服务器时间加8小时)
            map.put("CreateTime", LocalTimeUtil.getRealCurrentTime());

            // 验证ESN是否重复
            String esn = MapUtils.getString(map, "ESN", "");
            String amt = MapUtils.getString(map, "amtNo", "");
            if (StringUtils.isNotBlank(amt)) {
                int amtnum = customerAmtRelMapper.getRelationByUserIdAndAmt(userT.getId(), amt);
                if (amtnum > 0) {
                    ParameterTool.writeResponse(response, -15, "已添加变速箱号，不可重复添加！");
                    return null;
                }
            }

            if (StringUtils.isNotBlank(esn)) {
                int num = customerEngineRelDao.getRelationByUserIdAndESN(userT.getId(), esn);
                if (num > 0) {
                    ParameterTool.writeErrorResponse(response, -15);
                    return null;
                } else if (!this.esnByCheck(esn)) {
                    ParameterTool.writeErrorResponse(response, -46);
                    return null;
                } else {
                    //保存esn
                    this.customerEngineRelSave(esn, map);
                }
            }
            // amt 逻辑  保存

            if (StringUtils.isNotBlank(amt)) {
                int amtnum = customerAmtRelMapper.getRelationByUserIdAndAmt(userT.getId(), amt);
                if (amtnum > 0) {
                    ParameterTool.writeErrorResponse(response, -15);
                    return null;
                }
                this.saveCustomerAmtRel(map, amt);
            }
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

    /**
     * 根据用户id获取设备列表  增加amt工单
     */
    @Override
    public ModelAndView getCustomerEngineRelAndAmt(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        String keyword = MapUtils.getString(map, "keyword");
        String serviceChannel = MapUtils.getString(map, "serviceChannel");
        Map<String, Object> queryMap = new HashMap<>(2);
        queryMap.put("userId", userT.getId());
        queryMap.put("keyword", keyword);
        queryMap.put("serviceChannel", serviceChannel);
        List<Map<String, Object>> customerEngineRelList;
        if (!"DCEC".equals(serviceChannel)) {
            customerEngineRelList = customerEngineRelDao.getCustomerEngineRelList(queryMap);
        } else {
            customerEngineRelList = customerEngineRelDao.getCustomerEngineRelAndAmt(queryMap);
        }
        List<Map<String, Object>> dataList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(customerEngineRelList)) {
            for (Map<String, Object> dataMap : customerEngineRelList) {
                Map<String, Object> subData = new HashMap<>();
                subData.put("ID", MapUtils.getLong(dataMap, "cerID"));
                subData.put("EngineMsgId", MapUtils.getLong(dataMap, "id"));

                subData.put("SMN", MapUtils.getString(dataMap, "SMN", ""));
                if (StringUtils.isNotBlank(MapUtils.getString(dataMap, "ESN"))
                        && Pattern.matches(".*([A-Z]|[a-z])+.*", MapUtils.getString(dataMap, "ESN"))) {
                    if (MapUtils.getString(dataMap, "equipmentNo", "").equals(MapUtils.getString(dataMap, "ESN", ""))) {
                        subData.put("VIN", "");
                    } else {
                        subData.put("VIN", MapUtils.getString(dataMap, "equipmentNo", ""));
                    }
                } else {
                    subData.put("VIN", MapUtils.getString(dataMap, "equipmentNo", ""));
                }

                if (StringUtils.isNotBlank(MapUtils.getString(dataMap, "ESN"))
                        && Pattern.matches(".*([A-Z]|[a-z])+.*", MapUtils.getString(dataMap, "ESN"))) {
                    subData.put("ESN", "");
                } else {
                    subData.put("ESN", MapUtils.getString(dataMap, "ESN"));
                }

                subData.put("OEMID", 0L);
                //OEMName不取发动机表字段，取用户绑定设备表数据
                subData.put("OEMName", MapUtils.getString(dataMap, "OEMName", ""));
                subData.put("EngineType", MapUtils.getString(dataMap, "engineType", ""));
                subData.put("WarrantyStartDate", MapUtils.getString(dataMap, "WarrantyStartDate", ""));
                subData.put("Application", MapUtils.getString(dataMap, "Application", ""));
                subData.put("MarketType", MapUtils.getString(dataMap, "MarketType", ""));
                subData.put("ShoppingDate", MapUtils.getString(dataMap, "ShoppingDate", ""));
                //以下是ccec渠道所需字段
                subData.put("SONo", MapUtils.getString(dataMap, "SONo", ""));
                subData.put("Series", MapUtils.getString(dataMap, "Series", ""));
                subData.put("ISWarrantyStart", MapUtils.getIntValue(dataMap, "ISWarrantyStart", 2));
                //subData.put("engineType",MapUtils.getString(dataMap,"engineType",""));
                subData.put("EstimateWarrantyStartDate", MapUtils.getString(dataMap, "EstimateWarrantyStartDate", ""));
                subData.put("EngineProducedDate", MapUtils.getString(dataMap, "EngineProducedDate", ""));
                //是否是大运发动机
                int oemFlag = MapUtils.getIntValue(dataMap, "OEMFlag", 0);
                if (oemFlag == 1) {
                    subData.put("OEMFlag", 1);
                } else {
                    subData.put("OEMFlag", 0);
                }
                subData.put("EquipmentType", MapUtils.getString(dataMap, "EquipmentType", ""));
                subData.put("DrivingLicensePhotoUrl", MapUtils.getString(dataMap, "DrivingLicensePhotoUrl", ""));
                subData.put("EquipmentPhotoUrl", MapUtils.getString(dataMap, "EquipmentPhotoUrl", ""));
                subData.put("NewVIN", MapUtils.getString(dataMap, "NewVIN", ""));
                subData.put("EquipmentUse", MapUtils.getString(dataMap, "EquipmentUse", ""));
                subData.put("EquipmentUseName", MapUtils.getString(dataMap, "EquipmentUseName", ""));
                subData.put("ServiceStationId", MapUtils.getString(dataMap, "ServiceStationId", ""));
                subData.put("ServiceStationName", MapUtils.getString(dataMap, "ServiceStationName", ""));
                subData.put("EsnPowerType", MapUtils.getIntValue(dataMap, "EsnPowerType"));
                subData.put("EsnApplicationType", MapUtils.getIntValue(dataMap, "EsnApplicationType"));
                subData.put("CertifiedStatus", MapUtils.getIntValue(dataMap, "CertifiedStatus"));
                subData.put("AmtNo", MapUtils.getString(dataMap, "AmtNo"));
                dataList.add(subData);
            }
        }
        Map<String, Object> data = new HashMap<>(1);
        data.put("customerEngineRelList", dataList);
        ParameterTool.writeSuccessResponse(response, data);
        return null;
    }

    @Override
    @Transactional
    public ModelAndView updateCustomerEngineRelAmt(Map<String, Object> map) {
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String esn = MapUtils.getString(map, "ESN", "");
        String amt = MapUtils.getString(map, "amtNo", "");
        String vin = MapUtils.getString(map, "VIN", "");
//        int equipmentTypeIntValue = MapUtils.getIntValue(paramMap, "EquipmentType", -1);
        Long customerEngineRelID = MapUtils.getLong(map, "CustomerEngineRelID", -1L);
        String serviceChannel = MapUtils.getString(map, "serviceChannel", "");
        Integer amtType = MapUtils.getInteger(map, "amtType");
        if (customerEngineRelID == -1 || StringUtils.isBlank(serviceChannel) || null == amtType) {
            ParameterTool.writeResponse(response, 17, "缺少必要参数！");
            return null;
        }
        UserT userT = UserThreadLocal.get();
        if (amtType == 1) {
            if (StringUtils.isNotBlank(esn)) {
                //1代表 传入的amt，  验证esn是否重复  排除  esn和amt的修改的情况
                int countByCustomerAmtIdAndEsn = customerAmtRelMapper.getCountByCustomerAmtIdAndEsn(customerEngineRelID, esn);
                if (countByCustomerAmtIdAndEsn < 1) {
                    CustomerEngineRelT customerEngineRelByEsn = customerEngineRelDao.getCustomerEngineRelByEsn(userT.getId(), esn);
                    if (null != customerEngineRelByEsn) {
                        ParameterTool.writeErrorResponse(response, -15);
                        return null;
                    }
                }
            }
        } else {
            //0代表 传入的esn，  验证amt是否重复  排除  esn和amt的修改的情况
            if (StringUtils.isNotBlank(amt)) {
                int countByCustomerEngineIdAndEsn = customerAmtRelMapper.getCountByCustomerEngineIdAndEsn(customerEngineRelID, amt);
                if (countByCustomerEngineIdAndEsn < 1) {
                    CustomerAmtRel proRelationByUserIdAndAmt = customerAmtRelMapper.getProRelationByUserIdAndAmt(userT.getId(), amt);
                    if (null != proRelationByUserIdAndAmt) {
                        ParameterTool.writeErrorResponse(response, -15, "已添加变速箱号，不可重复添加！");
                        return null;
                    }
                }
            }
        }
        map.put("userId", userT.getId());
        if (StringUtils.isNotBlank(esn)) {
            CustomerEngineRelT customerEngineRelByEsn = customerEngineRelDao.getCustomerEngineRelByEsn(userT.getId(), esn);
            if (null != customerEngineRelByEsn) {
                this.customerEngineRelUpdate(map, customerEngineRelByEsn, vin, request);
            } else if (!this.esnByCheck(esn)) {
                ParameterTool.writeErrorResponse(response, -46);
                return null;
            } else {
                //添加 esn
                this.customerEngineRelSave(esn, map);
            }
        }
        if (StringUtils.isNotBlank(amt)) {
            CustomerAmtRel proRelationByUserIdAndAmt = customerAmtRelMapper.getProRelationByUserIdAndAmt(userT.getId(), amt);
            if (null != proRelationByUserIdAndAmt) {
                //更新操作
                this.updateCustomerAmtRel(map, proRelationByUserIdAndAmt);
            } else {
                //添加操作
                this.saveCustomerAmtRel(map, amt);
            }
        }
        ParameterTool.writeSuccessResponse(response);
        return null;
    }

    public void updateCustomerAmtRel(Map<String, Object> map, CustomerAmtRel proRelationByUserIdAndAmt) {
        String serviceChannel = MapUtils.getString(map, "serviceChannel", "");
        String amt = MapUtils.getString(map, "amtNo", "");
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        EngineMsg engineMsg = engineMsgDao.getEngineMsgByAmtNo(map);
        CRMResponeEntity cRMResponeEntity = CRMApiUtils.getCRMServiceApi().verifyEngineInfo(serviceChannel, amt);
        if (cRMResponeEntity.getStatus() == 0) {
            // 只有DBU存在status为0并且data为空的情况
            if (cRMResponeEntity.getData().size() == 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("customerInfoList", engineMsgService.getCustomerInfoListByAmt(amt, serviceChannel));
                ParameterTool.writeResponse(response, 2, "查无变速箱信息", data);
                return;
            }
            if (null != engineMsg) {
                Map<String, Object> engineMsgMap = new HashMap<>();
                engineMsgMap.put("id", engineMsg.getId());
//                engineMsgMap.put("equipmentNo", (cRMResponeEntity.getData().get("equipmentNo") != null ? cRMResponeEntity.getData().get("equipmentNo") : ""));
                engineMsgMap.put("equipmentNo", MapUtils.getString(map, "VIN"));
                engineMsgMap.put("vehicleCompany", (cRMResponeEntity.getData().get("vehicleCompany") != null ? cRMResponeEntity.getData().get("vehicleCompany") : ""));
                engineMsgMap.put("engineType", (cRMResponeEntity.getData().get("engineType") != null ? cRMResponeEntity.getData().get("engineType") : ""));
                engineMsgMap.put("manufactor", (cRMResponeEntity.getData().get("manufactor") != null ? cRMResponeEntity.getData().get("manufactor") : ""));
                engineMsgMap.put("serviceChannel", (cRMResponeEntity.getData().get("serviceChannel") != null ? cRMResponeEntity.getData().get("serviceChannel") : ""));
                engineMsgMap.put("saleDate", (cRMResponeEntity.getData().get("saleDate") != null ? cRMResponeEntity.getData().get("saleDate") : ""));
                engineMsgMap.put("marketType", (cRMResponeEntity.getData().get("marketTypes") != null ? cRMResponeEntity.getData().get("marketTypes") : ""));
                engineMsgMap.put("application", (cRMResponeEntity.getData().get("applications") != null ? cRMResponeEntity.getData().get("applications") : ""));
                engineMsgMap.put("warrantyStartDate", (cRMResponeEntity.getData().get("warrantyStartDate") != null ? cRMResponeEntity.getData().get("warrantyStartDate") : ""));
//                engineMsgMap.put("shoppingDate", (cRMResponeEntity.getData().get("shoppingDate") != null ? cRMResponeEntity.getData().get("shoppingDate") : ""));
                engineMsgMap.put("shoppingDate", MapUtils.getString(map, "shoppingDate", ""));
                engineMsgMap.put("amtNo", (cRMResponeEntity.getData().get("ESN") != null ? cRMResponeEntity.getData().get("ESN") : ""));
                engineMsgDao.updateEngineMsg(engineMsgMap);
                map.put("EngineMsgId", engineMsg.getId());
            } else {
                /**
                 * 发动机信息表EngineMsg中没有查询到数据，就根据变速箱号(amtNo)和服务渠道serviceChannel调用CRM接口查询变速箱数据
                 * 保存发动机信息表
                 */
                Map<String, Object> engineMsgMap = new HashedMap<String, Object>();
//                    engineMsgMap.put("ESN", map.get("ESN"));
                engineMsgMap.put("ESN", map.get("amtNo"));
                engineMsgMap.put("amtNo", map.get("amtNo"));
                engineMsgMap.put("SMN", cRMResponeEntity.getData().get("SMN"));
//                engineMsgMap.put("equipmentNo", (cRMResponeEntity.getData().get("equipmentNo") != null ? cRMResponeEntity.getData().get("equipmentNo") : ""));
                engineMsgMap.put("equipmentNo", MapUtils.getString(map, "VIN"));
                engineMsgMap.put("vehicleCompany", (cRMResponeEntity.getData().get("vehicleCompany") != null ? cRMResponeEntity.getData().get("vehicleCompany") : ""));
                engineMsgMap.put("engineType", (cRMResponeEntity.getData().get("engineType") != null ? cRMResponeEntity.getData().get("engineType") : ""));
                engineMsgMap.put("manufactor", (cRMResponeEntity.getData().get("manufactor") != null ? cRMResponeEntity.getData().get("manufactor") : ""));
                engineMsgMap.put("serviceChannel", (cRMResponeEntity.getData().get("serviceChannel") != null ? cRMResponeEntity.getData().get("serviceChannel") : ""));
                engineMsgMap.put("saleDate", (cRMResponeEntity.getData().get("saleDate") != null ? cRMResponeEntity.getData().get("saleDate") : ""));
                engineMsgMap.put("marketType", (cRMResponeEntity.getData().get("marketTypes") != null ? cRMResponeEntity.getData().get("marketTypes") : ""));
                engineMsgMap.put("application", (cRMResponeEntity.getData().get("applications") != null ? cRMResponeEntity.getData().get("applications") : ""));
                engineMsgMap.put("warrantyStartDate", (cRMResponeEntity.getData().get("warrantyStartDate") != null ? cRMResponeEntity.getData().get("warrantyStartDate") : ""));
//                engineMsgMap.put("shoppingDate", (cRMResponeEntity.getData().get("shoppingDate") != null ? cRMResponeEntity.getData().get("shoppingDate") : ""));
                engineMsgMap.put("shoppingDate", MapUtils.getString(map, "shoppingDate", ""));
                /**
                 * 保存变速箱信息
                 */
                engineMsgDao.insertEngineMsgByAmt(engineMsgMap);
                map.put("EngineMsgId", engineMsgMap.get("id"));
            }
            UserT userT = UserThreadLocal.get();
            proRelationByUserIdAndAmt.setUserId(userT.getId());
            proRelationByUserIdAndAmt.setPhone(MapUtils.getString(map, "phone"));
            proRelationByUserIdAndAmt.setVIN(MapUtils.getString(map, "VIN"));
            proRelationByUserIdAndAmt.setEngineMsgId(MapUtils.getLong(map, "EngineMsgId"));
            proRelationByUserIdAndAmt.setSMN(MapUtils.getLong(map, "EngineMsgId"));
            proRelationByUserIdAndAmt.setSMNName(MapUtils.getString(map, "SMNName"));
//            proRelationByUserIdAndAmt.setOEMID();
            proRelationByUserIdAndAmt.setOEMName(MapUtils.getString(map, "OEMName"));
            proRelationByUserIdAndAmt.setUpdator(userT.getId());
            proRelationByUserIdAndAmt.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
            proRelationByUserIdAndAmt.setServiceChannel(MapUtils.getString(map, "serviceChannel"));
            proRelationByUserIdAndAmt.setCustomerEngineRelId(MapUtils.getLong(map, "customerEngineRelId"));
            customerAmtRelMapper.updateByPrimaryKeySelective(proRelationByUserIdAndAmt);
        }
    }

    public void saveCustomerAmtRel(Map<String, Object> map, String amt) {
        EngineMsg engineMsg = engineMsgDao.getEngineMsgByAmtNo(map);
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String serviceChannel = MapUtils.getString(map, "serviceChannel", "");
        CRMResponeEntity cRMResponeEntity = CRMApiUtils.getCRMServiceApi().verifyEngineInfo(serviceChannel, amt);
        if (cRMResponeEntity.getStatus() == 0) {
            // 只有DBU存在status为0并且data为空的情况
            if (cRMResponeEntity.getData().size() == 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("customerInfoList", engineMsgService.getCustomerInfoListByAmt(amt, serviceChannel));
                ParameterTool.writeResponse(response, 2, "查无变速箱信息", data);
                return;
            }
            if (null != engineMsg) {
                Map<String, Object> engineMsgMap = new HashMap<>();
                engineMsgMap.put("id", engineMsg.getId());
                engineMsgMap.put("equipmentNo", MapUtils.getString(map, "VIN"));
                engineMsgMap.put("vehicleCompany", (cRMResponeEntity.getData().get("vehicleCompany") != null ? cRMResponeEntity.getData().get("vehicleCompany") : ""));
                engineMsgMap.put("engineType", (cRMResponeEntity.getData().get("engineType") != null ? cRMResponeEntity.getData().get("engineType") : ""));
                engineMsgMap.put("manufactor", (cRMResponeEntity.getData().get("manufactor") != null ? cRMResponeEntity.getData().get("manufactor") : ""));
                engineMsgMap.put("serviceChannel", (cRMResponeEntity.getData().get("serviceChannel") != null ? cRMResponeEntity.getData().get("serviceChannel") : ""));
                engineMsgMap.put("saleDate", (cRMResponeEntity.getData().get("saleDate") != null ? cRMResponeEntity.getData().get("saleDate") : ""));
                engineMsgMap.put("marketType", (cRMResponeEntity.getData().get("marketTypes") != null ? cRMResponeEntity.getData().get("marketTypes") : ""));
                engineMsgMap.put("application", (cRMResponeEntity.getData().get("applications") != null ? cRMResponeEntity.getData().get("applications") : ""));
                engineMsgMap.put("warrantyStartDate", (cRMResponeEntity.getData().get("warrantyStartDate") != null ? cRMResponeEntity.getData().get("warrantyStartDate") : ""));
//                engineMsgMap.put("shoppingDate", (cRMResponeEntity.getData().get("shoppingDate") != null ? cRMResponeEntity.getData().get("shoppingDate") : ""));
                engineMsgMap.put("shoppingDate", MapUtils.getString(map, "shoppingDate", ""));
                engineMsgMap.put("amtNo", (cRMResponeEntity.getData().get("ESN") != null ? cRMResponeEntity.getData().get("ESN") : ""));
                engineMsgDao.updateEngineMsg(engineMsgMap);
                map.put("EngineMsgId", engineMsg.getId());
            } else {
                /**
                 * 发动机信息表EngineMsg中没有查询到数据，就根据变速箱号(amtNo)和服务渠道serviceChannel调用CRM接口查询变速箱数据
                 * 保存发动机信息表
                 */
                Map<String, Object> engineMsgMap = new HashedMap<String, Object>();
//                    engineMsgMap.put("ESN", map.get("ESN"));
                engineMsgMap.put("ESN", map.get("amtNo"));
                engineMsgMap.put("amtNo", map.get("amtNo"));
                engineMsgMap.put("SMN", cRMResponeEntity.getData().get("SMN"));
                engineMsgMap.put("vehicleCompany", (cRMResponeEntity.getData().get("vehicleCompany") != null ? cRMResponeEntity.getData().get("vehicleCompany") : ""));
                engineMsgMap.put("engineType", (cRMResponeEntity.getData().get("engineType") != null ? cRMResponeEntity.getData().get("engineType") : ""));
                engineMsgMap.put("manufactor", (cRMResponeEntity.getData().get("manufactor") != null ? cRMResponeEntity.getData().get("manufactor") : ""));
                engineMsgMap.put("serviceChannel", (cRMResponeEntity.getData().get("serviceChannel") != null ? cRMResponeEntity.getData().get("serviceChannel") : ""));
                engineMsgMap.put("saleDate", (cRMResponeEntity.getData().get("saleDate") != null ? cRMResponeEntity.getData().get("saleDate") : ""));
                engineMsgMap.put("marketType", (cRMResponeEntity.getData().get("marketTypes") != null ? cRMResponeEntity.getData().get("marketTypes") : ""));
                engineMsgMap.put("application", (cRMResponeEntity.getData().get("applications") != null ? cRMResponeEntity.getData().get("applications") : ""));
                engineMsgMap.put("warrantyStartDate", (cRMResponeEntity.getData().get("warrantyStartDate") != null ? cRMResponeEntity.getData().get("warrantyStartDate") : ""));
//                engineMsgMap.put("shoppingDate", (cRMResponeEntity.getData().get("shoppingDate") != null ? cRMResponeEntity.getData().get("shoppingDate") : ""));
                engineMsgMap.put("shoppingDate", MapUtils.getString(map, "shoppingDate", ""));
                engineMsgMap.put("equipmentNo", MapUtils.getString(map, "VIN"));
                /**
                 * 保存变速箱信息
                 */
                engineMsgDao.insertEngineMsgByAmt(engineMsgMap);
                map.put("EngineMsgId", engineMsgMap.get("id"));
            }

            customerAmtRelMapper.addCustomerEngineRel(map);
        }
    }

    public void customerEngineRelSave(String esn, Map<String, Object> map) {
        EngineMsg engineMsg = engineMsgDao.getEngineMsgByESNString(esn);
        HttpServletRequest request = (HttpServletRequest) map.get("request");
        UserT userT = UserThreadLocal.get();
        //调用cip接口获取esn信息
        EsnBasicInfoEntity esnInfo = null;
        CipResponeEntity respone = CipApiUtils.getCipServiceApi().getEsnInfo(esn);
        if (null != respone) {
            map.put("cipReturnValue", JSON.toJSON(respone).toString());
            if (respone.getCode().equals(0)) {
                esnInfo = (EsnBasicInfoEntity) JSONObject.toBean(respone.getData(), EsnBasicInfoEntity.class);
            }
        }
        String smn = MapUtils.getString(map, "SMNName", "");
        Map<String, Object> engineMsgMap = new HashMap<>();
        int fleetEmissionLevelDInt = -1;
        int fleetFuelTypeDInt = -1;
        //设置排放信息
        if (null != esnInfo) {
            //排放等级
            String emissionLevel = esnInfo.getEmissionLevel();
            //燃油类型
            String fuelType = esnInfo.getFuelType();
            //获取字典表应用类型map(调用cip接口返回的应用类型枚举值)
            Map<String, Map<String, Object>> fleetEmissionLevelDicListMap = dictionariesTDao.getDicListByDtableName("fleetEmissionLevel");
            if (MapUtils.isNotEmpty(fleetEmissionLevelDicListMap) && StringUtils.isNotEmpty(emissionLevel) && fleetEmissionLevelDicListMap.containsKey(emissionLevel)) {
                Map<String, Object> fleetEmissionLevelDicMap = MapUtils.getObject(fleetEmissionLevelDicListMap, emissionLevel);
                if (MapUtils.isNotEmpty(fleetEmissionLevelDicMap)) {
                    fleetEmissionLevelDInt = MapUtils.getIntValue(fleetEmissionLevelDicMap, "DInt", -1);
                }
            }
            //获取字典表动力类型ma(调用cip接口返回的应用类型枚举值)
            Map<String, Map<String, Object>> fleetFuelTypeDicListMap = dictionariesTDao.getDicListByDtableName("fleetFuelType");
            if (MapUtils.isNotEmpty(fleetFuelTypeDicListMap) && StringUtils.isNotEmpty(fuelType) && fleetFuelTypeDicListMap.containsKey(fuelType)) {
                Map<String, Object> fleetFuelTypeDicMap = MapUtils.getObject(fleetFuelTypeDicListMap, fuelType);
                if (MapUtils.isNotEmpty(fleetFuelTypeDicMap)) {
                    fleetFuelTypeDInt = MapUtils.getIntValue(fleetFuelTypeDicMap, "DInt", -1);
                }
            }
            engineMsgMap.put("model", emissionLevel);
        }
        engineMsgMap.put("EsnPowerType", fleetFuelTypeDInt);
        engineMsgMap.put("EsnApplicationType", fleetEmissionLevelDInt);
        if (null == engineMsg) {
            engineMsgMap.put("ESN", MapUtils.getString(map, "ESN"));
            if (StringUtils.isEmpty(smn)) {  //如果前端传的smn是空的   调用sibel接口
                Map<String, Object> getSMNBySibel = workOrderTServiceImpl.getSMNBySibel(request, esn);
                if (MapUtils.isNotEmpty(getSMNBySibel)) {
                    Map<String, Object> data = (Map<String, Object>) MapUtils.getMap(getSMNBySibel, "data");
                    smn = MapUtils.getString(data, "SMN", "");
                }
            }
            engineMsgMap.put("SMN", smn);
//            engineMsgMap.put("equipmentNo", MapUtils.getString(map, "VIN"));
            if (StringUtils.isBlank(MapUtils.getString(map, "VIN"))) {
                map.put("VIN", MapUtils.getString(map, "ESN"));
            }
            engineMsgMap.put("equipmentNo", MapUtils.getString(map, "VIN"));
            engineMsgMap.put("vehicleCompany", MapUtils.getString(map, "OEMName"));
            engineMsgMap.put("engineType", MapUtils.getString(map, "engineType"));
            //engineMsgMap.put("manufactor", ""); //未传输
            engineMsgMap.put("serviceChannel", MapUtils.getString(map, "serviceChannel"));
            //engineMsgMap.put("saleDate", ""); //未传输
            engineMsgMap.put("marketType", MapUtils.getString(map, "marketType"));
            engineMsgMap.put("application", MapUtils.getString(map, "application"));
            engineMsgMap.put("warrantyStartDate", MapUtils.getString(map, "warrantyStartDate"));
            engineMsgMap.put("shoppingDate", MapUtils.getString(map, "shoppingDate"));
            //以下是ccec字段
            if ("CCEC".equals(MapUtils.getString(map, "serviceChannel", ""))) {
                engineMsgMap.put("series", MapUtils.getString(map, "series"));
                engineMsgMap.put("estimateWarrantyStartDate", MapUtils.getString(map, "estimateWarrantyStartDate"));
                engineMsgMap.put("soNo", MapUtils.getString(map, "soNo"));
                engineMsgMap.put("isWarrantyStart", MapUtils.getIntValue(map, "isWarrantyStart", 2));
            }
            //保存发动机信息
            engineMsgDao.newInsertEngineMsg(engineMsgMap);
            //将新插入发动机信息ID放入关联表中
            map.put("EngineMsgId", MapUtils.getLong(engineMsgMap, "id"));
        } else {
            if (StringUtils.isEmpty(smn) && StringUtils.isEmpty(engineMsg.getSMN())) {
                Map<String, Object> getSMNBySibel = workOrderTServiceImpl.getSMNBySibel(request, esn);
                if (MapUtils.isNotEmpty(getSMNBySibel)) {
                    Map<String, Object> data = (Map<String, Object>) MapUtils.getMap(getSMNBySibel, "data");
                    smn = MapUtils.getString(data, "SMN", "");
                }
            }
            if (StringUtils.isNotEmpty(smn)) {
                engineMsgMap.put("SMN", smn);
            }
//            engineMsgMap.put("equipmentNo", MapUtils.getString(map, "VIN"));
            if (StringUtils.isBlank(MapUtils.getString(map, "VIN"))) {
                map.put("VIN", MapUtils.getString(map, "ESN"));
                engineMsgMap.put("equipmentNo", engineMsg.getEquipmentNo());
            } else {
                engineMsgMap.put("equipmentNo", MapUtils.getString(map, "VIN"));
            }
            engineMsgMap.put("vehicleCompany", MapUtils.getString(map, "OEMName"));
            engineMsgMap.put("engineType", MapUtils.getString(map, "engineType"));
            //engineMsgMap.put("manufactor", ""); //未传输
            engineMsgMap.put("serviceChannel", MapUtils.getString(map, "serviceChannel"));
            //engineMsgMap.put("saleDate", ""); //未传输
            engineMsgMap.put("marketType", MapUtils.getString(map, "marketType"));
            engineMsgMap.put("application", MapUtils.getString(map, "application"));
            engineMsgMap.put("warrantyStartDate", MapUtils.getString(map, "warrantyStartDate"));
            engineMsgMap.put("shoppingDate", MapUtils.getString(map, "shoppingDate"));
            engineMsgMap.put("id", engineMsg.getId());
            //以下是ccec字段
            if ("CCEC".equals(MapUtils.getString(map, "serviceChannel", ""))) {
                engineMsgMap.put("series", MapUtils.getString(map, "series"));
                engineMsgMap.put("estimateWarrantyStartDate", MapUtils.getString(map, "estimateWarrantyStartDate"));
                engineMsgMap.put("soNo", MapUtils.getString(map, "soNo"));
                engineMsgMap.put("isWarrantyStart", MapUtils.getIntValue(map, "isWarrantyStart", 2));
            }
            if (null == esnInfo) {
                engineMsgMap.put("model", engineMsg.getModel());
            }
            engineMsgDao.updateEngineMsg(engineMsgMap);
            map.put("EngineMsgId", engineMsg.getId());
        }
        //活动绑车拉新
        //获取活动信息 活动期间报的问题
        ActivityT activity = inviteDao.getActivity(INVITE);
        if (null != activity && activity.getIsOpen().equals(1)
                && StringUtils.isNotEmpty(activity.getEndTime())
                && LocalTimeUtil.isBefore(LocalTimeUtil.getRealCurrentTime(), activity.getEndTime())) {
            int bindAddStatus = 0;
            if (null != esnInfo) {
                bindAddStatus = inviteUserService.addBind(esn, esnInfo.getEmissionLevel());
            } else {
                bindAddStatus = BindAddMessageStatus.BAOCUO.getStatus();
            }
            map.put("bindAddStatus", bindAddStatus);
            map.put("bindAddMessage", BindAddMessageStatus.getDescByCode(bindAddStatus));
        }
        //百万圆桌绑车
        inviteUserService.addBwyzBind(esn, userT.getId());
        //首次绑车添加蜜值
        int customerEngineRelTCount = customerEngineRelDao.getCountByUserId(userT.getId());
        if (customerEngineRelTCount <= 0) {
            //同步添加蜜值的方法
            syncAddhoney(request);
        }
        customerEngineRelDao.addCustomerEngineRel(map);
        map.put("customerEngineRelId", map.get("id"));
        Long count = saDao.isSignAgreement(userT.getId(), LocalTimeUtil.getRealCurrentTime());
        if (count > 0) {//用户如果签署了主动服务协议，将发动机信息同步至salesforce
            asyncCrmService.syncServiceAgreementAndEngineToCRM(userT, esn, true, true);
            //同步esn给cip
            List<String> esnList = new ArrayList<>();
            esnList.add(esn);
            CipApiUtils.getCipServiceApi().synchronizationEsn(ActionEnum.ADD.getValue(), esnList,null);
        }
        //月度报告
        String vinStr = MapUtils.getString(map, "VIN", "");
        syncEsnAndUserId.asSyncEsnAndUserIdAddOne(esn, vinStr, userT.getId(),null,"1", "","");
        //同步老友汇车辆
        externalDataSynchroService.pushLyhEsn(userT.getId(), esn, vinStr, "ADD");
    }

    public void customerEngineRelUpdate(Map<String, Object> paramMap, CustomerEngineRelT customerEngineRelT, String vin, HttpServletRequest request) {
        UserT userT = UserThreadLocal.get();
        paramMap.put("UserId", userT.getId());
        String realCurrentTime = LocalTimeUtil.getRealCurrentTime();
        paramMap.put("Updator", userT.getId());
        paramMap.put("UpdateTime", realCurrentTime);
        if (null != customerEngineRelT) {
            paramMap.put("customerEngineRelId", customerEngineRelT.getId());
            // 修改发动机信息表
            Map<String, Object> engineMsgMap = new HashMap<>();
            engineMsgMap.put("id", customerEngineRelT.getEngineMsgId());
            EngineMsg engineMsg = engineMsgDao.getEngineMsgById(customerEngineRelT.getEngineMsgId());
            String smn = MapUtils.getString(paramMap, "SMNName", "");

            EsnBasicInfoEntity esnInfo = null;
            String esn = MapUtils.getString(paramMap, "ESN", "");
            CipResponeEntity respone = CipApiUtils.getCipServiceApi().getEsnInfo(esn);
            if (null != respone) {
                paramMap.put("cipReturnValue", JSON.toJSON(respone).toString());
                if (respone.getCode().equals(0)) {
                    esnInfo = (EsnBasicInfoEntity) JSONObject.toBean(respone.getData(), EsnBasicInfoEntity.class);
                }
            }
            if (StringUtils.isEmpty(smn) && StringUtils.isEmpty(engineMsg.getSMN())) {
                Map<String, Object> getSMNBySibel = workOrderTServiceImpl.getSMNBySibel(request, esn);
                if (MapUtils.isNotEmpty(getSMNBySibel)) {
                    Map<String, Object> data = (Map<String, Object>) MapUtils.getMap(getSMNBySibel, "data");
                    smn = MapUtils.getString(data, "SMN", "");
                }
            }
            if (StringUtils.isNotEmpty(smn)) {
                engineMsgMap.put("SMN", smn);
            }
//            engineMsgMap.put("equipmentNo", MapUtils.getString(paramMap, "VIN"));
            if (StringUtils.isBlank(MapUtils.getString(paramMap, "VIN"))) {
                paramMap.put("VIN", MapUtils.getString(paramMap, "ESN"));
                engineMsgMap.put("equipmentNo", engineMsg.getEquipmentNo());
            } else {
                engineMsgMap.put("equipmentNo", MapUtils.getString(paramMap, "VIN"));
            }
            engineMsgMap.put("vehicleCompany", MapUtils.getString(paramMap, "OEMName"));
            engineMsgMap.put("engineType", MapUtils.getString(paramMap, "engineType"));
            //engineMsgMap.put("manufactor", ""); //未传输
            engineMsgMap.put("serviceChannel", MapUtils.getString(paramMap, "serviceChannel"));
            //engineMsgMap.put("saleDate", ""); //未传输
            engineMsgMap.put("marketType", MapUtils.getString(paramMap, "marketType"));
            engineMsgMap.put("application", MapUtils.getString(paramMap, "application"));
            engineMsgMap.put("warrantyStartDate", MapUtils.getString(paramMap, "warrantyStartDate"));
            engineMsgMap.put("shoppingDate", MapUtils.getString(paramMap, "shoppingDate"));
            engineMsgMap.put("id", engineMsg.getId());
            //以下是ccec字段
            if ("CCEC".equals(MapUtils.getString(paramMap, "serviceChannel", ""))) {
                engineMsgMap.put("series", MapUtils.getString(paramMap, "series"));
                engineMsgMap.put("estimateWarrantyStartDate", MapUtils.getString(paramMap, "estimateWarrantyStartDate"));
                engineMsgMap.put("soNo", MapUtils.getString(paramMap, "soNo"));
                engineMsgMap.put("isWarrantyStart", MapUtils.getIntValue(paramMap, "isWarrantyStart", 2));
            }
            if (null == esnInfo) {
                engineMsgMap.put("model", engineMsg.getModel());
            }
            engineMsgDao.updateEngineMsg(engineMsgMap);
            //修改用户和设备关联表
            customerEngineRelDao.newUpdateCustomerEngineRel(paramMap);
            //月度报告 修改 车牌号
            syncEsnAndUserId.asSyncEsnAndUserIdUpdateOne(customerEngineRelT.getEsn(), vin, userT.getId(),customerEngineRelT.getDrivingLicensePhotoUrl(),customerEngineRelT.getServiceChannel(),customerEngineRelT.getInviteCode(),customerEngineRelT.getSalesChannel());
            //同步老友汇车辆
            externalDataSynchroService.pushLyhEsn(userT.getId(), customerEngineRelT.getEsn(), vin, "UPDATE");
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ModelAndView deleteCustomerEngineRelAmt(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        map.put("userId", userT.getId());
        Long id = MapUtils.getLong(map, "ID", 0L);
        String amtNo = MapUtils.getString(map, "amtNo");
        if (StringUtils.isNotBlank(amtNo)) {
            CustomerAmtRel customerAmtRel = new CustomerAmtRel();
            customerAmtRel.setID(id);
            customerAmtRel.setFlag(-1);
            customerAmtRel.setUpdateTime(LocalTimeUtil.getRealCurrentTime());
            customerAmtRel.setUpdator(userT.getId());
            customerAmtRel.setDeleter(userT.getId());
            customerAmtRel.setDeleteTime(LocalTimeUtil.getRealCurrentTime());
            customerAmtRelMapper.updateByPrimaryKeySelective(customerAmtRel);
            CustomerAmtRel customerAmtRelSelect = customerAmtRelMapper.selectByPrimaryKey(id);
            if (null != customerAmtRelSelect && null != customerAmtRelSelect.getCustomerEngineRelId()) {
                map.put("ID", customerAmtRelSelect.getCustomerEngineRelId());
                this.closeCustomerEngineRel(map);
            }
        } else {
            this.closeCustomerEngineRel(map);
        }
        ParameterTool.writeSuccessResponse(response);
        return null;
    }

    public void closeCustomerEngineRel(Map<String, Object> map) {
        Long id = MapUtils.getLong(map, "ID", 0L);
        CustomerEngineRelT customerEngineRelT = customerEngineRelDao.getCustomerEngineRelById(id);
        UserT userT = UserThreadLocal.get();
        if (null != customerEngineRelT) {
            // 获取实际当前时间(服务器时间加8小时)
            String realCurrentTime = LocalTimeUtil.getRealCurrentTime();
            map.put("DeleteTime", realCurrentTime);
            customerEngineRelDao.deleteCustomerEngineRel(map);
            //调用公共方法
            userDeleteOrUnBindAuthPublicMethod(customerEngineRelT, userT, realCurrentTime, map);
        }
    }

    @Override
    public void updateAssociationType(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        String esn = MapUtils.getString(map, "ESN");
        String associationType = MapUtils.getString(map, "associationType");
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isBlank(esn)) {
            jsonObject.put("msg", "请输入esn");
            jsonObject.put("status", -99);
            ParameterTool.writeSuccessResponse(response, jsonObject);
            return;
        }
        if (StringUtils.isBlank(associationType)) {
            jsonObject.put("msg", "请输入associationType");
            jsonObject.put("status", -99);
            ParameterTool.writeSuccessResponse(response, jsonObject);
            return;
        }
        UserT userT = UserThreadLocal.get();
        CustomerEngineRelT customerEngineRelById = customerEngineRelDao.getCustomerEngineRelByEsn(userT.getId(), esn);
        if (customerEngineRelById != null) {
            if (customerEngineRelById.getAssociationType() == null) {
                Map<String, Object> param = new HashMap<>();
                param.put("CustomerEngineRelID", customerEngineRelById.getId());
                param.put("associationType", associationType); //  1为关联小蜜蜂
                customerEngineRelDao.newUpdateCustomerEngineRel(param);
                EngineMsg engineMsg = engineMsgDao.getEngineMsgById(customerEngineRelById.getEngineMsgId());
                if (null != engineMsg) {
                    Map<String, Object> engineMsgMap = new HashMap<>();
                    engineMsgMap.put("AssociationType", associationType);
                    engineMsgMap.put("id", engineMsg.getId());
                    engineMsgDao.updateEngineMsg(engineMsgMap);
                }
            } else {
                String[] split = customerEngineRelById.getAssociationType().split(",");
                List<String> collect = Arrays.stream(split).collect(Collectors.toList());
                if (!collect.contains(associationType)) {
                    Map<String, Object> param = new HashMap<>();
                    param.put("CustomerEngineRelID", customerEngineRelById.getId());
                    param.put("associationType", customerEngineRelById.getAssociationType() + "," + associationType); //  1为关联小蜜蜂
                    customerEngineRelDao.newUpdateCustomerEngineRel(param);
                    EngineMsg engineMsg = engineMsgDao.getEngineMsgById(customerEngineRelById.getEngineMsgId());
                    if (null != engineMsg) {
                        Map<String, Object> engineMsgMap = new HashMap<>();
                        engineMsgMap.put("AssociationType", customerEngineRelById.getAssociationType() + "," + associationType);
                        engineMsgMap.put("id", engineMsg.getId());
                        engineMsgDao.updateEngineMsg(engineMsgMap);
                    }
                }
            }
        }
        ParameterTool.writeSuccessResponse(response);
    }

    @Override
    public ModelAndView getCustomerEngineByEsnOrFirst(Map<String, Object> map) {
        HttpServletResponse response = (HttpServletResponse) map.get("response");
        UserT userT = UserThreadLocal.get();
        //用户是否签署协议
        Long count = saDao.isSignAgreement(userT.getId(), LocalTimeUtil.getRealCurrentTime());
        if (count <= 0) {
            ParameterTool.writeSuccessResponse(response, null);
            return null;
        }
        map.put("userId",userT.getId());
        String esn = MapUtils.getString(map,"esn");
        Map<String, Object> customerEngineByEsnOrFirst = null;
        if(StringUtils.isEmpty(esn)){
            //查询第一条数据
            List<Map<String, Object>> customerEngineRelList = customerEngineRelDao.getCustomerEngineRelList(map);
            if (CollectionUtils.isNotEmpty(customerEngineRelList)) {
                customerEngineByEsnOrFirst = customerEngineRelList.get(0);
            }
        }else{
            List<Map<String, Object>> engineByEsnOrFirst = this.customerEngineRelDao.getCustomerEngineByEsnOrFirst(esn, userT.getId());
            if (CollectionUtils.isEmpty(engineByEsnOrFirst)) {
                //查询第一条数据
                List<Map<String, Object>> customerEngineRelList = customerEngineRelDao.getCustomerEngineRelList(map);
                if (CollectionUtils.isNotEmpty(customerEngineRelList)) {
                    customerEngineByEsnOrFirst = customerEngineRelList.get(0);
                }
            }else {
                customerEngineByEsnOrFirst = engineByEsnOrFirst.get(0);
            }
        }
        ParameterTool.writeSuccessResponse(response, customerEngineByEsnOrFirst);
        return null;
    }

}
